Skip to main content

clickup_cli/
mcp.rs

1use crate::client::ClickUpClient;
2use crate::config::Config;
3use crate::git;
4use crate::output::{compact_items, flatten_value};
5use serde_json::{json, Value};
6use tokio::io::{AsyncBufReadExt, BufReader};
7
8pub mod classify;
9pub mod filter;
10pub mod pagination;
11
12// ── JSON-RPC helpers ──────────────────────────────────────────────────────────
13
14fn ok_response(id: &Value, result: Value) -> Value {
15    json!({"jsonrpc":"2.0","id":id,"result":result})
16}
17
18fn error_response(id: &Value, code: i64, message: &str) -> Value {
19    json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}})
20}
21
22fn tool_result(text: String) -> Value {
23    json!({"content":[{"type":"text","text":text}]})
24}
25
26fn tool_error(msg: String) -> Value {
27    json!({"content":[{"type":"text","text":msg}],"isError":true})
28}
29
30fn encode_query_value(value: &str) -> String {
31    value
32        .bytes()
33        .flat_map(|byte| match byte {
34            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
35                vec![byte as char]
36            }
37            _ => format!("%{:02X}", byte).chars().collect(),
38        })
39        .collect()
40}
41
42fn push_query_param(params: &mut Vec<String>, name: &str, value: impl ToString) {
43    params.push(format!(
44        "{}={}",
45        name,
46        encode_query_value(&value.to_string())
47    ));
48}
49
50fn push_string_array_query_params(
51    params: &mut Vec<String>,
52    args: &Value,
53    arg_name: &str,
54    query_name: &str,
55) {
56    if let Some(values) = args.get(arg_name).and_then(|v| v.as_array()) {
57        for value in values {
58            if let Some(value) = value.as_str() {
59                push_query_param(params, query_name, value);
60            }
61        }
62    }
63}
64
65fn push_number_array_query_params(
66    params: &mut Vec<String>,
67    args: &Value,
68    arg_name: &str,
69    query_name: &str,
70) {
71    if let Some(values) = args.get(arg_name).and_then(|v| v.as_array()) {
72        for value in values {
73            if let Some(value) = value.as_i64() {
74                push_query_param(params, query_name, value);
75            }
76        }
77    }
78}
79
80fn push_bool_query_param(params: &mut Vec<String>, args: &Value, arg_name: &str, query_name: &str) {
81    if let Some(value) = args.get(arg_name).and_then(|v| v.as_bool()) {
82        push_query_param(params, query_name, value);
83    }
84}
85
86fn push_i64_query_param(params: &mut Vec<String>, args: &Value, arg_name: &str, query_name: &str) {
87    if let Some(value) = args.get(arg_name).and_then(|v| v.as_i64()) {
88        push_query_param(params, query_name, value);
89    }
90}
91
92fn push_string_query_param(
93    params: &mut Vec<String>,
94    args: &Value,
95    arg_name: &str,
96    query_name: &str,
97) {
98    if let Some(value) = args.get(arg_name).and_then(|v| v.as_str()) {
99        push_query_param(params, query_name, value);
100    }
101}
102
103fn task_search_query_params(args: &Value) -> Vec<String> {
104    let mut params = Vec::new();
105
106    push_string_array_query_params(&mut params, args, "space_ids", "space_ids[]");
107    push_string_array_query_params(&mut params, args, "project_ids", "project_ids[]");
108    push_string_array_query_params(&mut params, args, "list_ids", "list_ids[]");
109    push_string_array_query_params(&mut params, args, "statuses", "statuses[]");
110    push_string_array_query_params(&mut params, args, "assignees", "assignees[]");
111    push_string_array_query_params(&mut params, args, "tags", "tags[]");
112    push_number_array_query_params(&mut params, args, "custom_items", "custom_items[]");
113
114    for key in [
115        "include_closed",
116        "subtasks",
117        "reverse",
118        "include_markdown_description",
119    ] {
120        push_bool_query_param(&mut params, args, key, key);
121    }
122
123    for key in [
124        "due_date_gt",
125        "due_date_lt",
126        "date_created_gt",
127        "date_created_lt",
128        "date_updated_gt",
129        "date_updated_lt",
130        "date_done_gt",
131        "date_done_lt",
132    ] {
133        push_i64_query_param(&mut params, args, key, key);
134    }
135
136    push_string_query_param(&mut params, args, "parent", "parent");
137    push_string_query_param(&mut params, args, "order_by", "order_by");
138
139    if let Some(custom_fields) = args.get("custom_fields").and_then(|v| v.as_array()) {
140        push_query_param(
141            &mut params,
142            "custom_fields",
143            serde_json::to_string(custom_fields).unwrap_or_else(|_| "[]".to_string()),
144        );
145    }
146
147    params
148}
149
150/// Inspects a `tools/call` request and returns a JSON-RPC response when the
151/// request can be resolved WITHOUT executing the tool itself (missing tool
152/// name, or tool is filtered out). Returns `None` when the caller should
153/// proceed to invoke the tool.
154pub fn handle_tools_call_early(
155    id: &Value,
156    params: &Value,
157    filter: &filter::Filter,
158) -> Option<Value> {
159    let tool_name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
160
161    if tool_name.is_empty() {
162        return Some(ok_response(id, tool_error("Missing tool name".to_string())));
163    }
164
165    if !filter.allows(tool_name) {
166        return Some(error_response(
167            id,
168            -32601,
169            &format!("Method not found: {} (filtered out at startup)", tool_name),
170        ));
171    }
172
173    None
174}
175
176// ── Tool definitions ──────────────────────────────────────────────────────────
177
178pub fn tool_list() -> Value {
179    json!([
180        {
181            "name": "clickup_whoami",
182            "description": "Get the currently authenticated ClickUp user",
183            "inputSchema": {
184                "type": "object",
185                "properties": {},
186                "required": []
187            }
188        },
189        {
190            "name": "clickup_workspace_list",
191            "description": "List all ClickUp workspaces (teams) accessible to the current user",
192            "inputSchema": {
193                "type": "object",
194                "properties": {},
195                "required": []
196            }
197        },
198        {
199            "name": "clickup_space_list",
200            "description": "List all spaces in a ClickUp workspace. Spaces are the top-level containers below the workspace and hold folders, lists, and tasks. Returns a compact array of space objects (id, name, private, archived). Use clickup_folder_list or clickup_list_list with a space_id to drill down.",
201            "inputSchema": {
202                "type": "object",
203                "properties": {
204                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config (defaults.workspace_id)."},
205                    "archived": {"type": "boolean", "description": "true = include archived spaces in the result; false or omitted = only active spaces. Defaults to false."}
206                },
207                "required": []
208            }
209        },
210        {
211            "name": "clickup_folder_list",
212            "description": "List all folders in a ClickUp space. Folders are optional groupings that contain lists; a space may also have folderless lists (use clickup_list_list with space_id for those). Returns a compact array of folder objects (id, name, task_count, archived).",
213            "inputSchema": {
214                "type": "object",
215                "properties": {
216                    "space_id": {"type": "string", "description": "ID of the parent space. Obtain from clickup_space_list (field: id)."},
217                    "archived": {"type": "boolean", "description": "true = include archived folders; false or omitted = only active folders. Defaults to false."}
218                },
219                "required": ["space_id"]
220            }
221        },
222        {
223            "name": "clickup_list_list",
224            "description": "List ClickUp lists under either a folder or a space (folderless lists). Exactly one of folder_id or space_id must be provided. Returns a compact array of list objects (id, name, task_count, archived). Use clickup_task_list to drill into a specific list.",
225            "inputSchema": {
226                "type": "object",
227                "properties": {
228                    "folder_id": {"type": "string", "description": "ID of the parent folder. Obtain from clickup_folder_list (field: id). Mutually exclusive with space_id."},
229                    "space_id": {"type": "string", "description": "ID of a space — returns only the folderless lists attached directly to the space. Obtain from clickup_space_list (field: id). Mutually exclusive with folder_id."},
230                    "archived": {"type": "boolean", "description": "true = include archived lists; false or omitted = only active lists. Defaults to false."}
231                },
232                "required": []
233            }
234        },
235        {
236            "name": "clickup_task_list",
237            "description": "List tasks in a specific ClickUp list with optional status/assignee filters. Returns the first page of task objects in compact form (id, name, status, assignees, due_date). Pass `page`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. For cross-list or cross-space queries use clickup_task_search instead; for a single task use clickup_task_get.",
238            "inputSchema": {
239                "type": "object",
240                "properties": {
241                    "list_id": {"type": "string", "description": "ID of the list to read tasks from. Obtain from clickup_list_list (field: id)."},
242                    "statuses": {
243                        "type": "array",
244                        "items": {"type": "string"},
245                        "description": "Status names to include (e.g. ['open','in progress']). Case-sensitive, must match a status defined on the list. Omit to return tasks in any open status."
246                    },
247                    "assignees": {
248                        "type": "array",
249                        "items": {"type": "string"},
250                        "description": "User IDs (as strings) to filter assignees. Obtain from clickup_member_list or clickup_user_get. Omit to return tasks regardless of assignee."
251                    },
252                    "include_closed": {"type": "boolean", "description": "true = include tasks whose status is in the 'closed' group; false or omitted = exclude closed tasks from the response."},
253                    "page": {"type": "integer", "minimum": 0, "description": "Zero-based ClickUp page index. Omit for page 0. When all=true, this is the starting page."},
254                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
255                    "all": {"type": "boolean", "description": "true = auto-fetch pages until ClickUp reports last_page=true or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
256                },
257                "required": ["list_id"]
258            }
259        },
260        {
261            "name": "clickup_task_get",
262            "description": "Fetch the full object for a single ClickUp task — name, description, status, assignees, tags, custom fields, checklists, due date, time estimates, dependencies, and more. Returns the task object. Use clickup_task_list or clickup_task_search to find a task_id.",
263            "inputSchema": {
264                "type": "object",
265                "properties": {
266                    "task_id": {"type": "string", "description": "ID of the task to fetch. Obtain from clickup_task_list (field: id) or clickup_task_search."},
267                    "include_subtasks": {"type": "boolean", "description": "true = include the task's subtasks in the response under the 'subtasks' field; false or omitted = return only the parent task."}
268                },
269                "required": ["task_id"]
270            }
271        },
272        {
273            "name": "clickup_task_create",
274            "description": "Create a new task in a ClickUp list. The task starts in the list's default status unless 'status' is supplied. Returns the created task object including its new id, which you can pass to clickup_task_update, clickup_task_get, etc.",
275            "inputSchema": {
276                "type": "object",
277                "properties": {
278                    "list_id": {"type": "string", "description": "ID of the list the task will live in. Obtain from clickup_list_list (field: id)."},
279                    "name": {"type": "string", "description": "Task title shown in the list view. Required and non-empty."},
280                    "description": {"type": "string", "description": "Task body. Markdown supported (headings, links, checkboxes, @mentions). Omit to create the task with no description."},
281                    "status": {"type": "string", "description": "Status name to start in (case-sensitive; must match a status configured on the list). Omit to use the list's default initial status."},
282                    "priority": {"type": "integer", "description": "Task priority: 1=Urgent, 2=High, 3=Normal, 4=Low. Omit for no priority."},
283                    "assignees": {
284                        "type": "array",
285                        "items": {"type": "integer"},
286                        "description": "User IDs to assign to the task. Obtain from clickup_member_list or clickup_user_get. Omit for an unassigned task."
287                    },
288                    "tags": {
289                        "type": "array",
290                        "items": {"type": "string"},
291                        "description": "Tag names to apply. Tags must already exist in the parent space (use clickup_tag_list to see available tags or clickup_tag_create to add new ones)."
292                    },
293                    "due_date": {"type": "integer", "description": "Due date as a Unix timestamp in milliseconds (e.g. 1735689600000 for 2025-01-01). Omit for no due date."}
294                },
295                "required": ["list_id", "name"]
296            }
297        },
298        {
299            "name": "clickup_task_update",
300            "description": "Update fields on an existing ClickUp task — name, description, status, priority, and incrementally add/remove assignees. Only provided fields are changed; omitted fields keep their current value. For tags use clickup_task_add_tag/remove_tag; for moving between lists use clickup_task_move. Returns the updated task object.",
301            "inputSchema": {
302                "type": "object",
303                "properties": {
304                    "task_id": {"type": "string", "description": "ID of the task to update. Obtain from clickup_task_list (field: id) or clickup_task_search."},
305                    "name": {"type": "string", "description": "New task title. Omit to keep current name."},
306                    "status": {"type": "string", "description": "New status name (case-sensitive, must match a status defined on the parent list). Omit to keep current status."},
307                    "priority": {"type": "integer", "description": "New priority: 1=Urgent, 2=High, 3=Normal, 4=Low. Omit to keep current priority."},
308                    "description": {"type": "string", "description": "New task body — replaces the current description entirely. Markdown supported. Omit to keep current description."},
309                    "add_assignees": {
310                        "type": "array",
311                        "items": {"type": "integer"},
312                        "description": "User IDs to add as assignees (additive; does not replace existing assignees). Obtain from clickup_member_list."
313                    },
314                    "rem_assignees": {
315                        "type": "array",
316                        "items": {"type": "integer"},
317                        "description": "User IDs to remove from assignees (no-op if the user is not currently assigned)."
318                    },
319                    "time_estimate": {"type": "integer", "description": "New total time estimate in milliseconds. Omit to keep current estimate."}
320                },
321                "required": ["task_id"]
322            }
323        },
324        {
325            "name": "clickup_task_delete",
326            "description": "Permanently delete a ClickUp task along with all its subtasks, comments, checklists, attachments, and time entries. Destructive, irreversible, and cascading — confirm with the user before calling. To mark a task done without deleting, use clickup_task_update with a 'closed' status instead. Returns an empty object on success.",
327            "inputSchema": {
328                "type": "object",
329                "properties": {
330                    "task_id": {"type": "string", "description": "ID of the task to delete. Obtain from clickup_task_list (field: id) or clickup_task_search. All subtasks, comments, checklists, attachments, and time entries on this task are deleted with it."}
331                },
332                "required": ["task_id"]
333            }
334        },
335        {
336            "name": "clickup_task_search",
337            "description": "Search tasks across an entire ClickUp workspace with ClickUp's filtered team tasks endpoint. Supports hierarchy, assignee, status, tag, date range, custom field, custom item type, parent/subtask, and ordering filters. Returns a compact array of task objects. Pass `page`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. For tasks in a single list, prefer clickup_task_list (fewer parameters, same shape).",
338            "inputSchema": {
339                "type": "object",
340                "properties": {
341                    "team_id": {"type": "string", "description": "Workspace (team) ID to search within. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
342                    "space_ids": {
343                        "type": "array",
344                        "items": {"type": "string"},
345                        "description": "Restrict results to these space IDs. Obtain from clickup_space_list (field: id). Omit to search all spaces."
346                    },
347                    "project_ids": {
348                        "type": "array",
349                        "items": {"type": "string"},
350                        "description": "Restrict results to these folder/project IDs. ClickUp's API parameter is project_ids[]. Obtain IDs from clickup_folder_list."
351                    },
352                    "list_ids": {
353                        "type": "array",
354                        "items": {"type": "string"},
355                        "description": "Restrict results to these list IDs. Obtain from clickup_list_list (field: id). Omit to search all lists."
356                    },
357                    "statuses": {
358                        "type": "array",
359                        "items": {"type": "string"},
360                        "description": "Status names to include (e.g. ['open','in review']). Case-sensitive. Omit for any open status."
361                    },
362                    "assignees": {
363                        "type": "array",
364                        "items": {"type": "string"},
365                        "description": "User IDs (as strings) to restrict to tasks assigned to them. Obtain from clickup_member_list. Omit to return tasks regardless of assignee."
366                    },
367                    "tags": {
368                        "type": "array",
369                        "items": {"type": "string"},
370                        "description": "Tag names to filter by. Tags must match ClickUp tag names in the relevant spaces."
371                    },
372                    "include_closed": {"type": "boolean", "description": "true = include tasks in closed statuses; false or omitted = exclude closed tasks."},
373                    "subtasks": {"type": "boolean", "description": "true = include subtasks in search results; false or omitted = exclude subtasks unless parent is provided."},
374                    "parent": {"type": "string", "description": "Parent task ID. When set, returns subtasks under this parent task."},
375                    "order_by": {"type": "string", "description": "Sort field supported by ClickUp, such as id, created, updated, or due_date."},
376                    "reverse": {"type": "boolean", "description": "true = reverse the selected sort order."},
377                    "due_date_gt": {"type": "integer", "description": "Filter tasks with due_date greater than this Unix timestamp in milliseconds."},
378                    "due_date_lt": {"type": "integer", "description": "Filter tasks with due_date less than this Unix timestamp in milliseconds."},
379                    "date_created_gt": {"type": "integer", "description": "Filter tasks created after this Unix timestamp in milliseconds."},
380                    "date_created_lt": {"type": "integer", "description": "Filter tasks created before this Unix timestamp in milliseconds."},
381                    "date_updated_gt": {"type": "integer", "description": "Filter tasks updated after this Unix timestamp in milliseconds."},
382                    "date_updated_lt": {"type": "integer", "description": "Filter tasks updated before this Unix timestamp in milliseconds."},
383                    "date_done_gt": {"type": "integer", "description": "Filter tasks completed after this Unix timestamp in milliseconds."},
384                    "date_done_lt": {"type": "integer", "description": "Filter tasks completed before this Unix timestamp in milliseconds."},
385                    "custom_fields": {
386                        "type": "array",
387                        "items": {"type": "object"},
388                        "description": "ClickUp custom field filters. Each object is sent inside the custom_fields JSON query parameter, e.g. [{\"field_id\":\"...\",\"operator\":\"=\",\"value\":\"...\"}]. Use operators supported by ClickUp, including IS NULL / IS NOT NULL for unset/set checks."
389                    },
390                    "custom_items": {
391                        "type": "array",
392                        "items": {"type": "integer"},
393                        "description": "Filter by ClickUp custom task type IDs. Include 0 for regular tasks, 1 for milestones, or workspace-defined custom item type IDs."
394                    },
395                    "include_markdown_description": {"type": "boolean", "description": "true = ask ClickUp to return task descriptions in Markdown format."},
396                    "page": {"type": "integer", "minimum": 0, "description": "Zero-based ClickUp page index. Omit for page 0. When all=true, this is the starting page."},
397                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
398                    "all": {"type": "boolean", "description": "true = auto-fetch pages until ClickUp reports last_page=true or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
399                },
400                "required": []
401            }
402        },
403        {
404            "name": "clickup_comment_list",
405            "description": "List comments on a ClickUp task in chronological order (newest first). Only top-level comments are returned; use clickup_comment_replies to fetch a threaded reply chain. Returns a compact array of comment objects (id, comment_text, user, date). Pass `start`/`start_id`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. ClickUp's comment endpoints use start-id-based pagination: to fetch the next page, pass the previous response's `pagination.next_start` and `pagination.next_start_id`.",
406            "inputSchema": {
407                "type": "object",
408                "properties": {
409                    "task_id": {"type": "string", "description": "ID of the task to read comments from. Obtain from clickup_task_list (field: id) or clickup_task_search."},
410                    "start": {"type": "integer", "description": "Unix millisecond timestamp of the boundary comment — pass the previous response's `pagination.next_start`. Required as a pair with `start_id`. Omit for the first page."},
411                    "start_id": {"type": "string", "description": "Comment ID matching the `start` timestamp — pass the previous response's `pagination.next_start_id`. Required as a pair with `start`. Omit for the first page."},
412                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
413                    "all": {"type": "boolean", "description": "true = auto-fetch pages until the server returns a short page (< 25 items) or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
414                },
415                "required": ["task_id"]
416            }
417        },
418        {
419            "name": "clickup_comment_create",
420            "description": "Post a new top-level comment on a ClickUp task. @mentions are recognised by ClickUp. Note: ClickUp's v2 comment API stores the body verbatim and does NOT render markdown. Tokens like `**bold**` appear as literal characters in the UI. Returns the created comment object including its new id, which you can pass to clickup_comment_reply, clickup_comment_update, etc.",
421            "inputSchema": {
422                "type": "object",
423                "properties": {
424                    "task_id": {"type": "string", "description": "ID of the task to comment on. Obtain from clickup_task_list (field: id) or clickup_task_search."},
425                    "text": {"type": "string", "description": "Comment body. @mentions (e.g. '@username') are rendered. Markdown is NOT rendered by ClickUp's v2 comment API. Markdown syntax is stored as literal text."},
426                    "assignee": {"type": "integer", "description": "Optional user ID to assign the comment to — they will receive a notification. Obtain from clickup_member_list."},
427                    "notify_all": {"type": "boolean", "description": "true = send a notification to every assignee of the task; false or omitted = only notify people mentioned or the explicit assignee."}
428                },
429                "required": ["task_id", "text"]
430            }
431        },
432        {
433            "name": "clickup_field_list",
434            "description": "List the custom field definitions available on a ClickUp list — field id, name, type (text, number, drop_down, labels, date, url, email, phone, money, progress, formula, etc.), and for drop_down/labels fields the permitted option values extracted from type_config.options. Use this before clickup_field_set to learn the correct field_id, option ids, and value shape. Returns an array of custom field definitions.",
435            "inputSchema": {
436                "type": "object",
437                "properties": {
438                    "list_id": {"type": "string", "description": "ID of the list whose custom fields to enumerate. Obtain from clickup_list_list (field: id). Fields are defined per-list (or inherited from folder/space)."}
439                },
440                "required": ["list_id"]
441            }
442        },
443        {
444            "name": "clickup_field_set",
445            "description": "Set or overwrite a single custom field value on a ClickUp task. The value's JSON shape must match the field type (string for text/url/email and for a drop_down option id, number for number/currency/progress, array of option ids for labels, Unix ms for date, etc.). Use clickup_field_list first to see the field type and option ids. Use clickup_field_unset to clear a value. Returns an empty object on success.",
446            "inputSchema": {
447                "type": "object",
448                "properties": {
449                    "task_id": {"type": "string", "description": "ID of the task whose field value should change. Obtain from clickup_task_list (field: id)."},
450                    "field_id": {"type": "string", "description": "ID of the custom field to set. Obtain from clickup_field_list (field: id) or clickup_task_get (custom_fields[].id)."},
451                    "value": {"description": "New value; the accepted type depends on the custom field type. Examples: 'hello' (text), 42 (number), 'option-uuid' (drop_down), ['option-uuid'] (labels), 1735689600000 (date as Unix ms). See clickup_field_list for the field's type and option ids."}
452                },
453                "required": ["task_id", "field_id", "value"]
454            }
455        },
456        {
457            "name": "clickup_time_start",
458            "description": "Start a live time-tracking timer for the authenticated user. If a timer is already running it will be stopped first. Pair with clickup_time_stop to end the timer and record the entry. Use clickup_time_current to inspect the running timer. Returns the newly started time entry object.",
459            "inputSchema": {
460                "type": "object",
461                "properties": {
462                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
463                    "task_id": {"type": "string", "description": "ID of the task to attribute this timer to. Obtain from clickup_task_list (field: id). Omit to track time without a task."},
464                    "description": {"type": "string", "description": "Free-text description shown on the time entry (e.g. 'pair debugging session'). Optional."},
465                    "billable": {"type": "boolean", "description": "true = mark this time entry as billable (shows as $ in reports); false or omitted = non-billable."}
466                },
467                "required": []
468            }
469        },
470        {
471            "name": "clickup_time_stop",
472            "description": "Stop the currently running time tracking entry",
473            "inputSchema": {
474                "type": "object",
475                "properties": {
476                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."}
477                },
478                "required": []
479            }
480        },
481        {
482            "name": "clickup_time_list",
483            "description": "List historical time tracking entries for a workspace, optionally filtered by date range and/or task. Covers both manually-created entries and stopped timers. Returns a compact array of time entry objects (id, user, task, start, duration, billable, description).",
484            "inputSchema": {
485                "type": "object",
486                "properties": {
487                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
488                    "start_date": {"type": "integer", "description": "Inclusive lower bound as a Unix timestamp in milliseconds (e.g. 1735689600000 for 2025-01-01). Omit for no lower bound."},
489                    "end_date": {"type": "integer", "description": "Inclusive upper bound as a Unix timestamp in milliseconds. Omit for no upper bound. Note: ClickUp caps the range to ~30 days by default."},
490                    "task_id": {"type": "string", "description": "Return only entries attributed to this task. Obtain from clickup_task_list (field: id). Omit to list entries across all tasks."}
491                },
492                "required": []
493            }
494        },
495        {
496            "name": "clickup_checklist_create",
497            "description": "Create a new checklist (to-do group) on a ClickUp task. The checklist starts empty — add items via clickup_checklist_add_item. A task can have multiple checklists. Returns the created checklist object including its new id.",
498            "inputSchema": {
499                "type": "object",
500                "properties": {
501                    "task_id": {"type": "string", "description": "ID of the task to attach the checklist to. Obtain from clickup_task_list (field: id)."},
502                    "name": {"type": "string", "description": "Display name for the checklist (e.g. 'Launch prep', 'QA steps'). Shown as a heading above the items."}
503                },
504                "required": ["task_id", "name"]
505            }
506        },
507        {
508            "name": "clickup_checklist_delete",
509            "description": "Permanently delete an entire checklist from a ClickUp task, including all its items. Destructive and irreversible. To remove a single item instead, use clickup_checklist_delete_item. Returns an empty object on success.",
510            "inputSchema": {
511                "type": "object",
512                "properties": {
513                    "checklist_id": {"type": "string", "description": "ID of the checklist to delete. Obtain from clickup_task_get (field: checklists[].id). All items on this checklist are deleted with it."}
514                },
515                "required": ["checklist_id"]
516            }
517        },
518        {
519            "name": "clickup_goal_list",
520            "description": "List all ClickUp goals in a workspace. Each goal represents an OKR-style objective and can have multiple key results (sub-targets). Returns a compact array of goal objects (id, name, percent_completed, due_date). Use clickup_goal_get for the full goal including its key_results.",
521            "inputSchema": {
522                "type": "object",
523                "properties": {
524                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."}
525                },
526                "required": []
527            }
528        },
529        {
530            "name": "clickup_goal_get",
531            "description": "Fetch a single ClickUp goal including its key results, owners, due date, and current percent-complete. Returns the goal object with its key_results array populated.",
532            "inputSchema": {
533                "type": "object",
534                "properties": {
535                    "goal_id": {"type": "string", "description": "ID of the goal to fetch. Obtain from clickup_goal_list (field: id). The authenticated user must have view access to the goal's workspace."}
536                },
537                "required": ["goal_id"]
538            }
539        },
540        {
541            "name": "clickup_goal_create",
542            "description": "Create a new OKR-style goal in a workspace. The goal starts with zero key results — add them via clickup_goal_add_kr. The goal's percent-complete is auto-calculated from the average progress of its key results. Returns the created goal object including its new id.",
543            "inputSchema": {
544                "type": "object",
545                "properties": {
546                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
547                    "name": {"type": "string", "description": "Goal title (e.g. 'Q1 revenue target'). Required and non-empty."},
548                    "due_date": {"type": "integer", "description": "Target completion date as a Unix timestamp in milliseconds (e.g. 1735689600000 for 2025-01-01)."},
549                    "description": {"type": "string", "description": "Goal description / rationale. Markdown supported. Omit for no description."},
550                    "owner_ids": {
551                        "type": "array",
552                        "items": {"type": "integer"},
553                        "description": "User IDs to assign as goal owners (they receive notifications about progress). Obtain from clickup_member_list."
554                    }
555                },
556                "required": ["name"]
557            }
558        },
559        {
560            "name": "clickup_goal_update",
561            "description": "Modify a ClickUp goal's top-level fields (name, description, due date). To change progress, update the goal's key results instead via clickup_goal_update_kr — the goal's percent complete is derived automatically. Returns the updated goal object.",
562            "inputSchema": {
563                "type": "object",
564                "properties": {
565                    "goal_id": {"type": "string", "description": "ID of the goal to update. Obtain from clickup_goal_list (field: id)."},
566                    "name": {"type": "string", "description": "New goal title. Omit to keep current name."},
567                    "due_date": {"type": "integer", "description": "New due date as a Unix timestamp in milliseconds (e.g. 1735689600000 for 2025-01-01)."},
568                    "description": {"type": "string", "description": "New goal description. Markdown supported."}
569                },
570                "required": ["goal_id"]
571            }
572        },
573        {
574            "name": "clickup_view_list",
575            "description": "List saved views (board, list, calendar, gantt, timeline, etc.) attached to a space, folder, list, or the whole workspace. Exactly one of space_id/folder_id/list_id must be provided — or omit all three to list workspace-level views. Returns a compact array of view objects (id, name, type).",
576            "inputSchema": {
577                "type": "object",
578                "properties": {
579                    "space_id": {"type": "string", "description": "Space ID whose views to list. Obtain from clickup_space_list. Mutually exclusive with folder_id/list_id."},
580                    "folder_id": {"type": "string", "description": "Folder ID whose views to list. Obtain from clickup_folder_list. Mutually exclusive with space_id/list_id."},
581                    "list_id": {"type": "string", "description": "List ID whose views to list. Obtain from clickup_list_list. Mutually exclusive with space_id/folder_id."},
582                    "team_id": {"type": "string", "description": "Workspace (team) ID — used when all three scope IDs are omitted, to return workspace-level (Everything) views. Obtain from clickup_workspace_list. Omit to use the default workspace from config."}
583                },
584                "required": []
585            }
586        },
587        {
588            "name": "clickup_view_tasks",
589            "description": "Fetch the tasks currently visible in a ClickUp view, honouring the view's configured filters, sort order, and grouping. Returns a compact array of task objects. Pass `page`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. Use clickup_view_list to discover view IDs and clickup_view_get for the view's definition.",
590            "inputSchema": {
591                "type": "object",
592                "properties": {
593                    "view_id": {"type": "string", "description": "ID of the view to read tasks from. Obtain from clickup_view_list (field: id)."},
594                    "page": {"type": "integer", "minimum": 0, "description": "Zero-based ClickUp page index. Omit for page 0. When all=true, this is the starting page."},
595                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
596                    "all": {"type": "boolean", "description": "true = auto-fetch pages until ClickUp reports last_page=true or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
597                },
598                "required": ["view_id"]
599            }
600        },
601        {
602            "name": "clickup_doc_list",
603            "description": "List all ClickUp docs in a workspace. Docs are long-form markdown documents separate from tasks and can contain nested pages. Returns a compact array of doc objects (id, name, date_created, date_updated). Pass `cursor`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. Use clickup_doc_get for a single doc or clickup_doc_pages to list a doc's pages.",
604            "inputSchema": {
605                "type": "object",
606                "properties": {
607                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
608                    "cursor": {"type": "string", "description": "Opaque pagination cursor from a previous response's `pagination.next_cursor`. Omit for the first page."},
609                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
610                    "all": {"type": "boolean", "description": "true = auto-fetch pages until next_cursor is empty or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
611                },
612                "required": []
613            }
614        },
615        {
616            "name": "clickup_doc_get",
617            "description": "Fetch metadata for a single ClickUp doc — name, parent, dates, type. Does not return the page bodies; use clickup_doc_pages (with content=true) or clickup_doc_get_page for the markdown content. Returns the doc object.",
618            "inputSchema": {
619                "type": "object",
620                "properties": {
621                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
622                    "doc_id": {"type": "string", "description": "ID of the doc to fetch. Obtain from clickup_doc_list (field: id)."}
623                },
624                "required": ["doc_id"]
625            }
626        },
627        {
628            "name": "clickup_doc_pages",
629            "description": "List the pages inside a ClickUp doc, including any nested subpages. Returns an array of page objects (id, name, sub_title, parent_page_id, and optionally content). Pages are ordered by their tree position.",
630            "inputSchema": {
631                "type": "object",
632                "properties": {
633                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
634                    "doc_id": {"type": "string", "description": "ID of the parent doc. Obtain from clickup_doc_list (field: id)."},
635                    "content": {"type": "boolean", "description": "true = include each page's full markdown body in the 'content' field; false or omitted = return page metadata only (faster, smaller payload)."}
636                },
637                "required": ["doc_id"]
638            }
639        },
640        {
641            "name": "clickup_tag_list",
642            "description": "List all tags defined in a ClickUp space. Tags are space-scoped labels (with foreground/background hex colours) that can be applied to tasks within that space. Returns an array of tag objects (name, tag_fg, tag_bg, creator).",
643            "inputSchema": {
644                "type": "object",
645                "properties": {
646                    "space_id": {"type": "string", "description": "ID of the space whose tags to list. Obtain from clickup_space_list (field: id). Tags are defined per-space, not workspace-wide."}
647                },
648                "required": ["space_id"]
649            }
650        },
651        {
652            "name": "clickup_task_add_tag",
653            "description": "Attach an existing tag to a ClickUp task. The tag must already be defined in the task's parent space — use clickup_tag_list to check and clickup_tag_create to add a new tag first. Tags are identified by name, not ID. Returns an empty object on success.",
654            "inputSchema": {
655                "type": "object",
656                "properties": {
657                    "task_id": {"type": "string", "description": "ID of the task to tag. Obtain from clickup_task_list (field: id)."},
658                    "tag_name": {"type": "string", "description": "Name of the tag to apply (case-sensitive, must already exist in the task's space). Obtain from clickup_tag_list."}
659                },
660                "required": ["task_id", "tag_name"]
661            }
662        },
663        {
664            "name": "clickup_task_remove_tag",
665            "description": "Detach a tag from a ClickUp task. The tag definition itself is preserved in the space — only this task's association with it is removed. No-op if the tag was not on the task. Returns an empty object on success.",
666            "inputSchema": {
667                "type": "object",
668                "properties": {
669                    "task_id": {"type": "string", "description": "ID of the task to untag. Obtain from clickup_task_list (field: id) or clickup_task_get."},
670                    "tag_name": {"type": "string", "description": "Name of the tag to remove (case-sensitive). See clickup_task_get (field: tags[].name) for tags currently on the task."}
671                },
672                "required": ["task_id", "tag_name"]
673            }
674        },
675        {
676            "name": "clickup_webhook_list",
677            "description": "List all webhooks registered on a ClickUp workspace. Each webhook specifies a target endpoint, subscribed events, and optional scope. Returns an array of webhook objects (id, endpoint, events, status, secret, health). Use clickup_webhook_create/update/delete to manage them.",
678            "inputSchema": {
679                "type": "object",
680                "properties": {
681                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."}
682                },
683                "required": []
684            }
685        },
686        {
687            "name": "clickup_member_list",
688            "description": "List members (users with direct access) of a specific task or list. Exactly one of task_id or list_id must be provided. Returns an array of user objects (id, username, email, color). Use clickup_user_invite to add people to the workspace first; use clickup_guest_share_task/list to add guests.",
689            "inputSchema": {
690                "type": "object",
691                "properties": {
692                    "task_id": {"type": "string", "description": "Task ID whose members to list. Obtain from clickup_task_list (field: id). Mutually exclusive with list_id."},
693                    "list_id": {"type": "string", "description": "List ID whose members to list. Obtain from clickup_list_list (field: id). Mutually exclusive with task_id."}
694                },
695                "required": []
696            }
697        },
698        {
699            "name": "clickup_template_list",
700            "description": "List the task templates available in a workspace. Task templates are saved task shapes (name, description, checklists, subtasks, custom fields, etc.) that can be applied via clickup_template_apply_task to create new tasks quickly. Returns a compact array of template objects (id, name). Pass `page`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array.",
701            "inputSchema": {
702                "type": "object",
703                "properties": {
704                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
705                    "page": {"type": "integer", "minimum": 0, "description": "Zero-based ClickUp page index. Omit for page 0. When all=true, this is the starting page."},
706                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
707                    "all": {"type": "boolean", "description": "true = auto-fetch pages until ClickUp reports last_page=true or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
708                },
709                "required": []
710            }
711        },
712        {
713            "name": "clickup_space_get",
714            "description": "Fetch the full object for a single ClickUp space — name, privacy, statuses, features (time tracking, tags, due dates enabled, etc.), and members. Returns the space object. Use clickup_folder_list or clickup_list_list to enumerate the space's contents.",
715            "inputSchema": {
716                "type": "object",
717                "properties": {
718                    "space_id": {"type": "string", "description": "ID of the space to fetch. Obtain from clickup_space_list (field: id)."}
719                },
720                "required": ["space_id"]
721            }
722        },
723        {
724            "name": "clickup_space_create",
725            "description": "Create a new top-level space in a ClickUp workspace. The new space uses the workspace's default feature set and statuses — customise later via the web UI or by creating folders/lists under it. Returns the created space object including its new id.",
726            "inputSchema": {
727                "type": "object",
728                "properties": {
729                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
730                    "name": {"type": "string", "description": "Display name for the space (shown in the sidebar)."},
731                    "private": {"type": "boolean", "description": "true = private space (only explicit members see it); false or omitted = visible to the whole workspace."}
732                },
733                "required": ["name"]
734            }
735        },
736        {
737            "name": "clickup_space_update",
738            "description": "Modify a ClickUp space — rename it, toggle privacy, or archive/unarchive it. Archiving is the reversible alternative to deletion: archived spaces are hidden from default views but retain all their folders, lists, and tasks. Returns the updated space object.",
739            "inputSchema": {
740                "type": "object",
741                "properties": {
742                    "space_id": {"type": "string", "description": "ID of the space to update. Obtain from clickup_space_list (field: id)."},
743                    "name": {"type": "string", "description": "New space name. Omit to keep current name."},
744                    "private": {"type": "boolean", "description": "true = space is private (visible only to explicit members); false = space is visible to the whole workspace."},
745                    "archived": {"type": "boolean", "description": "true = archive (hide but preserve); false = restore from archive."}
746                },
747                "required": ["space_id"]
748            }
749        },
750        {
751            "name": "clickup_space_delete",
752            "description": "Permanently delete a ClickUp space along with every folder, list, and task inside it. Destructive, irreversible, and widely cascading — confirm with the user before calling. To hide a space without destroying its contents, use clickup_space_update with archived=true instead (archival is reversible). Returns an empty object on success.",
753            "inputSchema": {
754                "type": "object",
755                "properties": {
756                    "space_id": {"type": "string", "description": "ID of the space to delete. Obtain from clickup_space_list (field: id). All descendant folders, lists, and tasks are deleted with it."}
757                },
758                "required": ["space_id"]
759            }
760        },
761        {
762            "name": "clickup_folder_get",
763            "description": "Fetch the full object for a single ClickUp folder — name, task_count (a string, per API), archived status, and its child lists. Returns the folder object. Use clickup_list_list with folder_id to get just the lists.",
764            "inputSchema": {
765                "type": "object",
766                "properties": {
767                    "folder_id": {"type": "string", "description": "ID of the folder to fetch. Obtain from clickup_folder_list (field: id)."}
768                },
769                "required": ["folder_id"]
770            }
771        },
772        {
773            "name": "clickup_folder_create",
774            "description": "Create a new folder inside a ClickUp space. Folders group related lists and start empty — add lists via clickup_list_create with folder_id. Returns the created folder object including its new id.",
775            "inputSchema": {
776                "type": "object",
777                "properties": {
778                    "space_id": {"type": "string", "description": "ID of the parent space. Obtain from clickup_space_list (field: id)."},
779                    "name": {"type": "string", "description": "Display name for the folder. Must be non-empty and unique within the space."}
780                },
781                "required": ["space_id", "name"]
782            }
783        },
784        {
785            "name": "clickup_folder_update",
786            "description": "Rename a ClickUp folder. Only the folder's display name can be changed via this endpoint — to move the folder to a different space, delete and recreate. Returns the updated folder object.",
787            "inputSchema": {
788                "type": "object",
789                "properties": {
790                    "folder_id": {"type": "string", "description": "ID of the folder to rename. Obtain from clickup_folder_list (field: id) or clickup_folder_get."},
791                    "name": {"type": "string", "description": "New display name for the folder. Must be non-empty and unique within its parent space."}
792                },
793                "required": ["folder_id", "name"]
794            }
795        },
796        {
797            "name": "clickup_folder_delete",
798            "description": "Permanently delete a ClickUp folder along with every list and task inside it. Destructive, irreversible, and cascading — confirm with the user before calling. If you only want to hide the folder, use clickup_space_update with archived=true on the parent space instead (archival is reversible). Returns an empty object on success.",
799            "inputSchema": {
800                "type": "object",
801                "properties": {
802                    "folder_id": {"type": "string", "description": "ID of the folder to delete. Obtain from clickup_folder_list (field: id). All descendant lists and tasks are deleted with it."}
803                },
804                "required": ["folder_id"]
805            }
806        },
807        {
808            "name": "clickup_list_get",
809            "description": "Fetch the full object for a single ClickUp list — name, content/description, statuses, task_count, assignees, due date, and parent folder/space. Returns the list object. Use clickup_task_list with list_id to enumerate tasks inside it.",
810            "inputSchema": {
811                "type": "object",
812                "properties": {
813                    "list_id": {"type": "string", "description": "ID of the list to fetch. Obtain from clickup_list_list (field: id)."}
814                },
815                "required": ["list_id"]
816            }
817        },
818        {
819            "name": "clickup_list_create",
820            "description": "Create a new task list inside either a folder or a space (folderless). Exactly one of folder_id or space_id must be provided. Returns the created list object including its new id — use it as list_id for clickup_task_create and related calls.",
821            "inputSchema": {
822                "type": "object",
823                "properties": {
824                    "folder_id": {"type": "string", "description": "ID of the parent folder. Obtain from clickup_folder_list (field: id). Mutually exclusive with space_id."},
825                    "space_id": {"type": "string", "description": "ID of the parent space — creates a folderless list attached directly to the space. Obtain from clickup_space_list (field: id). Mutually exclusive with folder_id."},
826                    "name": {"type": "string", "description": "Display name for the list. Required and non-empty."},
827                    "content": {"type": "string", "description": "List description shown at the top of the list. Markdown supported. Omit for no description."},
828                    "due_date": {"type": "integer", "description": "List-level due date as a Unix timestamp in milliseconds (e.g. 1735689600000 for 2025-01-01). Individual tasks retain their own due dates."},
829                    "status": {"type": "string", "description": "Default status for tasks added to this list. Must match a status name from the parent space's status set."}
830                },
831                "required": ["name"]
832            }
833        },
834        {
835            "name": "clickup_list_update",
836            "description": "Modify a ClickUp list's name, description, due date, or status. To move tasks between lists use clickup_task_move, and to add or remove this list from tasks with multi-list membership use clickup_list_add_task / clickup_list_remove_task. Returns the updated list object.",
837            "inputSchema": {
838                "type": "object",
839                "properties": {
840                    "list_id": {"type": "string", "description": "ID of the list to update. Obtain from clickup_list_list (field: id)."},
841                    "name": {"type": "string", "description": "New list name. Omit to keep current name."},
842                    "content": {"type": "string", "description": "New description for the list. Markdown supported."},
843                    "due_date": {"type": "integer", "description": "List-level due date as a Unix timestamp in milliseconds. Individual tasks retain their own due dates."},
844                    "status": {"type": "string", "description": "Default status for tasks added to this list (must match an existing status name in the list's status set)."}
845                },
846                "required": ["list_id"]
847            }
848        },
849        {
850            "name": "clickup_list_delete",
851            "description": "Permanently delete a ClickUp list along with every task inside it, plus their comments, checklists, and attachments. Destructive, irreversible, and cascading — confirm with the user before calling. To move tasks elsewhere first, use clickup_task_move on each, or use clickup_list_update to rename/archive instead. Returns an empty object on success.",
852            "inputSchema": {
853                "type": "object",
854                "properties": {
855                    "list_id": {"type": "string", "description": "ID of the list to delete. Obtain from clickup_list_list (field: id). All tasks inside are deleted with it."}
856                },
857                "required": ["list_id"]
858            }
859        },
860        {
861            "name": "clickup_list_add_task",
862            "description": "Add a task to a secondary list (multi-list membership) without moving it. The task remains in its original home list and becomes additionally visible in this one — useful for shared roadmaps. To change the home list instead, use clickup_task_move. Returns an empty object on success.",
863            "inputSchema": {
864                "type": "object",
865                "properties": {
866                    "list_id": {"type": "string", "description": "ID of the secondary list the task should also appear in. Obtain from clickup_list_list (field: id)."},
867                    "task_id": {"type": "string", "description": "ID of the task to add. Obtain from clickup_task_list (field: id)."}
868                },
869                "required": ["list_id", "task_id"]
870            }
871        },
872        {
873            "name": "clickup_list_remove_task",
874            "description": "Remove a task from a secondary list it was added to via clickup_list_add_task. The task itself is NOT deleted — it remains in its home list (and any other secondary lists). Use clickup_task_delete to remove the task entirely. Returns an empty object on success.",
875            "inputSchema": {
876                "type": "object",
877                "properties": {
878                    "list_id": {"type": "string", "description": "ID of the secondary list to detach the task from. Obtain from clickup_list_list (field: id). Must not be the task's home list."},
879                    "task_id": {"type": "string", "description": "ID of the task to detach. Obtain from clickup_task_list (field: id)."}
880                },
881                "required": ["list_id", "task_id"]
882            }
883        },
884        {
885            "name": "clickup_comment_update",
886            "description": "Edit the text, assignee, or resolution state of a ClickUp comment on a task, list, or view. The entire comment body is replaced by the new text (no partial edits). Marking resolved=true strikes through the comment and closes the thread. Returns the updated comment object.",
887            "inputSchema": {
888                "type": "object",
889                "properties": {
890                    "comment_id": {"type": "string", "description": "ID of the comment to edit. Obtain from clickup_comment_list (field: id)."},
891                    "text": {"type": "string", "description": "Replacement body for the comment. @mentions (e.g. '@username') are rendered. Markdown is NOT rendered by ClickUp's v2 comment API; markdown syntax is stored as literal text. The previous body is overwritten entirely."},
892                    "assignee": {"type": "integer", "description": "Reassign the comment to this user ID, who will receive a notification. Obtain from clickup_member_list."},
893                    "resolved": {"type": "boolean", "description": "true = mark the comment thread resolved/closed; false = reopen it."}
894                },
895                "required": ["comment_id", "text"]
896            }
897        },
898        {
899            "name": "clickup_comment_delete",
900            "description": "Permanently delete a ClickUp comment from a task, list, or view. Destructive and irreversible — the comment and any threaded replies are removed. Use clickup_comment_update with resolved=true instead if you only want to mark the comment as handled. Returns an empty object on success.",
901            "inputSchema": {
902                "type": "object",
903                "properties": {
904                    "comment_id": {"type": "string", "description": "ID of the comment to delete. Obtain from clickup_comment_list (field: id). The authenticated user must have edit permission on the parent task/list/view."}
905                },
906                "required": ["comment_id"]
907            }
908        },
909        {
910            "name": "clickup_task_add_dep",
911            "description": "Create a dependency relationship between two tasks — either 'task_id depends on depends_on' (blocks until that is done) or 'dependency_of depends on task_id' (task_id blocks that). Provide exactly one of depends_on or dependency_of. Use clickup_task_link for a simple non-blocking reference. Returns an empty object on success.",
912            "inputSchema": {
913                "type": "object",
914                "properties": {
915                    "task_id": {"type": "string", "description": "ID of the primary task. Obtain from clickup_task_list (field: id)."},
916                    "depends_on": {"type": "string", "description": "ID of a task that task_id should wait for (task_id is blocked until depends_on is complete). Obtain from clickup_task_list. Mutually exclusive with dependency_of."},
917                    "dependency_of": {"type": "string", "description": "ID of a task that depends on task_id (that task is blocked until task_id is complete). Obtain from clickup_task_list. Mutually exclusive with depends_on."}
918                },
919                "required": ["task_id"]
920            }
921        },
922        {
923            "name": "clickup_task_remove_dep",
924            "description": "Remove an existing dependency relationship between two tasks. Provide exactly one of depends_on or dependency_of, matching the direction you set with clickup_task_add_dep. The tasks themselves are not affected. Returns an empty object on success.",
925            "inputSchema": {
926                "type": "object",
927                "properties": {
928                    "task_id": {"type": "string", "description": "ID of the primary task in the dependency. Obtain from clickup_task_list (field: id) or clickup_task_get (field: dependencies[])."},
929                    "depends_on": {"type": "string", "description": "ID of the upstream task to detach from task_id (removes the 'task_id waits for this' edge). Mutually exclusive with dependency_of."},
930                    "dependency_of": {"type": "string", "description": "ID of the downstream task to detach (removes the 'this waits for task_id' edge). Mutually exclusive with depends_on."}
931                },
932                "required": ["task_id"]
933            }
934        },
935        {
936            "name": "clickup_task_link",
937            "description": "Create a bidirectional reference link between two tasks — a non-blocking 'see also' relationship, unlike dependencies. Both tasks show the other in their 'Linked tasks' panel. Use clickup_task_unlink to remove. For blocking relationships, use clickup_task_add_dep instead. Returns an empty object on success.",
938            "inputSchema": {
939                "type": "object",
940                "properties": {
941                    "task_id": {"type": "string", "description": "ID of the first task. Obtain from clickup_task_list (field: id)."},
942                    "links_to": {"type": "string", "description": "ID of the second task to link to. Obtain from clickup_task_list (field: id). The link is visible from both tasks."}
943                },
944                "required": ["task_id", "links_to"]
945            }
946        },
947        {
948            "name": "clickup_task_unlink",
949            "description": "Remove a bidirectional reference link previously created with clickup_task_link. The tasks themselves are not affected, only the link between them. No-op if no link exists. Returns an empty object on success.",
950            "inputSchema": {
951                "type": "object",
952                "properties": {
953                    "task_id": {"type": "string", "description": "ID of the first task. Obtain from clickup_task_list (field: id) or clickup_task_get (field: linked_tasks[])."},
954                    "links_to": {"type": "string", "description": "ID of the linked task to unlink from task_id."}
955                },
956                "required": ["task_id", "links_to"]
957            }
958        },
959        {
960            "name": "clickup_goal_delete",
961            "description": "Permanently delete a ClickUp goal along with all its key results. Destructive, irreversible, and cascading — confirm with the user before calling. Historical progress data on the goal is lost. Returns an empty object on success.",
962            "inputSchema": {
963                "type": "object",
964                "properties": {
965                    "goal_id": {"type": "string", "description": "ID of the goal to delete. Obtain from clickup_goal_list (field: id) or clickup_goal_get. All child key results are deleted with it."}
966                },
967                "required": ["goal_id"]
968            }
969        },
970        {
971            "name": "clickup_goal_add_kr",
972            "description": "Add a new key result (KR / sub-target) to a ClickUp goal. KRs drive the goal's overall percent-complete — each KR's progress is averaged. For 'automatic' KRs, link tasks or lists and progress is derived from their status; for number/currency/percentage KRs, report progress via clickup_goal_update_kr. Returns the created key result object.",
973            "inputSchema": {
974                "type": "object",
975                "properties": {
976                    "goal_id": {"type": "string", "description": "ID of the parent goal. Obtain from clickup_goal_list (field: id)."},
977                    "name": {"type": "string", "description": "Display name of the key result (e.g. 'MRR reaches $50k')."},
978                    "type": {"type": "string", "description": "Key result type: 'number' (numeric target), 'currency' (monetary target), 'boolean' (done/not-done), 'percentage' (0–100), or 'automatic' (derived from linked tasks/lists)."},
979                    "steps_start": {"type": "number", "description": "Starting value of the metric (e.g. 0 for a from-zero KR, current baseline otherwise). Ignored for 'boolean'."},
980                    "steps_end": {"type": "number", "description": "Target value the KR aims to reach. For 'percentage' KRs use 100; for 'boolean' use 1."},
981                    "unit": {"type": "string", "description": "Unit label shown next to numeric values (e.g. 'USD', 'users', 'signups'). Ignored for 'boolean' and 'automatic'."},
982                    "owner_ids": {"type": "array", "items": {"type": "integer"}, "description": "User IDs responsible for this KR. Obtain from clickup_member_list."},
983                    "task_ids": {"type": "array", "items": {"type": "string"}, "description": "Task IDs whose completion drives progress (only for type='automatic'). Obtain from clickup_task_list."},
984                    "list_ids": {"type": "array", "items": {"type": "string"}, "description": "List IDs whose task-completion percentage drives progress (only for type='automatic'). Obtain from clickup_list_list."}
985                },
986                "required": ["goal_id", "name", "type", "steps_start", "steps_end"]
987            }
988        },
989        {
990            "name": "clickup_goal_update_kr",
991            "description": "Update a key result (sub-target) on a ClickUp goal — typically to record current progress, rename, or adjust the unit label. The goal's completion percentage is auto-recalculated from all its key results. Returns the updated key result object.",
992            "inputSchema": {
993                "type": "object",
994                "properties": {
995                    "kr_id": {"type": "string", "description": "Key result ID. Obtain from clickup_goal_get (field: key_results[].id) or the response of clickup_goal_add_kr."},
996                    "steps_current": {"type": "number", "description": "Current progress toward steps_end. For boolean KRs use 0 (not done) or 1 (done). For percentage KRs use 0–100."},
997                    "name": {"type": "string", "description": "New display name for the key result. Omit to keep current name."},
998                    "unit": {"type": "string", "description": "Unit label shown next to numeric values (e.g. 'MRR', 'users'). Ignored for boolean and automatic types."}
999                },
1000                "required": ["kr_id"]
1001            }
1002        },
1003        {
1004            "name": "clickup_goal_delete_kr",
1005            "description": "Permanently delete a single key result from a ClickUp goal. Destructive and irreversible — the historical progress for this key result is lost, and the goal's overall completion percentage is recalculated from the remaining key results. Returns an empty object on success.",
1006            "inputSchema": {
1007                "type": "object",
1008                "properties": {
1009                    "kr_id": {"type": "string", "description": "ID of the key result to delete. Obtain from clickup_goal_get (field: key_results[].id)."}
1010                },
1011                "required": ["kr_id"]
1012            }
1013        },
1014        {
1015            "name": "clickup_time_get",
1016            "description": "Fetch the full object for a single time tracking entry — user, task, start timestamp, duration, description, billable flag, and tags. Returns the time entry object.",
1017            "inputSchema": {
1018                "type": "object",
1019                "properties": {
1020                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1021                    "timer_id": {"type": "string", "description": "ID of the time entry. Obtain from clickup_time_list (field: id) or clickup_time_current."}
1022                },
1023                "required": ["timer_id"]
1024            }
1025        },
1026        {
1027            "name": "clickup_time_create",
1028            "description": "Manually record a historical time tracking entry with a fixed start and duration. Use this for backfilling time (e.g. work done offline). For live timing use clickup_time_start/stop instead. Returns the created time entry object including its new id.",
1029            "inputSchema": {
1030                "type": "object",
1031                "properties": {
1032                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1033                    "task_id": {"type": "string", "description": "ID of the task to attribute the time to. Obtain from clickup_task_list. Omit for a task-less time entry."},
1034                    "start": {"type": "integer", "description": "Entry start time as a Unix timestamp in milliseconds (e.g. 1735689600000 for 2025-01-01 00:00 UTC)."},
1035                    "duration": {"type": "integer", "description": "Duration in milliseconds (e.g. 3600000 for one hour)."},
1036                    "description": {"type": "string", "description": "Free-text description of the work logged. Optional."},
1037                    "billable": {"type": "boolean", "description": "true = mark as billable (shows with $ in reports); false or omitted = non-billable."}
1038                },
1039                "required": ["start", "duration"]
1040            }
1041        },
1042        {
1043            "name": "clickup_time_update",
1044            "description": "Modify a recorded time tracking entry. Only the supplied fields are changed; omitted fields keep their current value. Use clickup_time_add_tags / remove_tags for tag changes. Returns the updated time entry object.",
1045            "inputSchema": {
1046                "type": "object",
1047                "properties": {
1048                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1049                    "timer_id": {"type": "string", "description": "ID of the time entry to update. Obtain from clickup_time_list (field: id)."},
1050                    "start": {"type": "integer", "description": "New start time as a Unix timestamp in milliseconds. Omit to keep current start."},
1051                    "duration": {"type": "integer", "description": "New duration in milliseconds (e.g. 3600000 for one hour). Omit to keep current duration."},
1052                    "description": {"type": "string", "description": "New description for the entry. Omit to keep current description."},
1053                    "billable": {"type": "boolean", "description": "true = billable, false = non-billable. Omit to keep current value."}
1054                },
1055                "required": ["timer_id"]
1056            }
1057        },
1058        {
1059            "name": "clickup_time_delete",
1060            "description": "Permanently delete a recorded time tracking entry. Destructive and irreversible — the logged time is removed from reports. To stop a currently running timer, use clickup_time_stop instead (which preserves the record). Returns an empty object on success.",
1061            "inputSchema": {
1062                "type": "object",
1063                "properties": {
1064                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1065                    "timer_id": {"type": "string", "description": "ID of the time entry to delete. Obtain from clickup_time_list (field: id). Only the entry's owner (or a workspace admin) can delete it."}
1066                },
1067                "required": ["timer_id"]
1068            }
1069        },
1070        {
1071            "name": "clickup_view_get",
1072            "description": "Fetch the full definition of a single ClickUp view — name, type (list/board/calendar/gantt/etc.), parent scope, filters, grouping, sort order, and column layout. Does not return the tasks inside the view; use clickup_view_tasks for that. Returns the view object.",
1073            "inputSchema": {
1074                "type": "object",
1075                "properties": {
1076                    "view_id": {"type": "string", "description": "ID of the view to fetch. Obtain from clickup_view_list (field: id)."}
1077                },
1078                "required": ["view_id"]
1079            }
1080        },
1081        {
1082            "name": "clickup_view_create",
1083            "description": "Create a new saved view (board, list, calendar, timeline, etc.) attached to a space, folder, list, or the workspace. Creates an empty view with default filters — customise filters/grouping/sort later via the web UI. Returns the created view object including its new id.",
1084            "inputSchema": {
1085                "type": "object",
1086                "properties": {
1087                    "scope": {"type": "string", "description": "Where to attach the view: 'space', 'folder', 'list', or 'team' (workspace-level 'Everything' view)."},
1088                    "scope_id": {"type": "string", "description": "ID of the scope object. For scope='space' use a space_id, for 'folder' a folder_id, for 'list' a list_id, for 'team' a workspace/team id (from clickup_workspace_list)."},
1089                    "name": {"type": "string", "description": "Display name for the view."},
1090                    "type": {"type": "string", "description": "View type: 'list', 'board', 'calendar', 'table', 'timeline', 'gantt', 'map', 'workload', 'activity', 'chat', 'mind_map', 'doc', or 'form'."}
1091                },
1092                "required": ["scope", "scope_id", "name", "type"]
1093            }
1094        },
1095        {
1096            "name": "clickup_view_update",
1097            "description": "Rename a view or change its display type (e.g. from list to board). To change filters, grouping, or sort order, use the ClickUp web UI — those are not exposed via the API. Returns the updated view object.",
1098            "inputSchema": {
1099                "type": "object",
1100                "properties": {
1101                    "view_id": {"type": "string", "description": "ID of the view to update. Obtain from clickup_view_list (field: id)."},
1102                    "name": {"type": "string", "description": "New display name for the view."},
1103                    "type": {"type": "string", "description": "New view type: 'list', 'board', 'calendar', 'table', 'timeline', 'gantt', 'map', 'workload', 'activity', 'chat', 'mind_map', 'doc', or 'form'."}
1104                },
1105                "required": ["view_id", "name", "type"]
1106            }
1107        },
1108        {
1109            "name": "clickup_view_delete",
1110            "description": "Permanently delete a ClickUp view (board, list, calendar, gantt, etc.). Destructive and irreversible for custom views — default views cannot be deleted and will return a 400 error. The underlying tasks are not affected, only the view definition. Returns an empty object on success.",
1111            "inputSchema": {
1112                "type": "object",
1113                "properties": {
1114                    "view_id": {"type": "string", "description": "ID of the view to delete. Obtain from clickup_view_list (field: id). Must be a user-created view, not a ClickUp-default one."}
1115                },
1116                "required": ["view_id"]
1117            }
1118        },
1119        {
1120            "name": "clickup_doc_create",
1121            "description": "Create a new ClickUp doc in a workspace. The doc starts with no pages — add pages via clickup_doc_add_page. Optionally attach the doc under a parent space/folder/list/task instead of the workspace root. Returns the created doc object including its new id.",
1122            "inputSchema": {
1123                "type": "object",
1124                "properties": {
1125                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1126                    "name": {"type": "string", "description": "Display name for the doc (shown in the doc tree)."},
1127                    "parent": {"type": "object", "description": "Optional parent object to attach the doc under. Shape: { 'id': '<id>', 'type': <int> } where type is 4=space, 5=folder, 6=list, 7=everything, 12=workspace. Omit to create at the workspace root."}
1128                },
1129                "required": ["name"]
1130            }
1131        },
1132        {
1133            "name": "clickup_doc_add_page",
1134            "description": "Create a new page inside an existing ClickUp doc. Pages support a markdown body plus optional subtitle. Supply parent_page_id to nest the page under another page (creates a page tree). Returns the created page object including its new id, which you can pass to clickup_doc_edit_page or clickup_doc_get_page.",
1135            "inputSchema": {
1136                "type": "object",
1137                "properties": {
1138                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."},
1139                    "doc_id": {"type": "string", "description": "ID of the parent doc. Obtain from clickup_doc_list (field: id)."},
1140                    "name": {"type": "string", "description": "Title shown in the doc's left-hand page navigator."},
1141                    "content": {"type": "string", "description": "Initial body of the page in ClickUp-flavoured markdown. Omit to create an empty page you can populate later via clickup_doc_edit_page."},
1142                    "sub_title": {"type": "string", "description": "Optional subtitle rendered under the page title."},
1143                    "parent_page_id": {"type": "string", "description": "ID of a sibling page to nest this page under. Omit to create a top-level page. Obtain from clickup_doc_pages (field: id)."}
1144                },
1145                "required": ["doc_id", "name"]
1146            }
1147        },
1148        {
1149            "name": "clickup_doc_edit_page",
1150            "description": "Rename or rewrite an existing page inside a ClickUp doc. By default the supplied content replaces the current page body. Pass mode='append' or mode='prepend' to merge with the existing body instead. For a fresh page use clickup_doc_add_page instead. Returns the updated page object.",
1151            "inputSchema": {
1152                "type": "object",
1153                "properties": {
1154                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1155                    "doc_id": {"type": "string", "description": "ID of the parent doc. Obtain from clickup_doc_list (field: id)."},
1156                    "page_id": {"type": "string", "description": "ID of the page to edit. Obtain from clickup_doc_pages (field: id)."},
1157                    "name": {"type": "string", "description": "New page title. Omit to keep current title."},
1158                    "content": {"type": "string", "description": "New page body in ClickUp-flavoured markdown. Replaces the existing body unless mode is set. Omit to leave content unchanged."},
1159                    "mode": {"type": "string", "description": "How to combine content with the existing body: 'replace' (default), 'append', or 'prepend'. Sent as content_edit_mode on the wire."}
1160                },
1161                "required": ["doc_id", "page_id"]
1162            }
1163        },
1164        {
1165            "name": "clickup_chat_channel_create",
1166            "description": "Create a new ClickUp Chat channel in a workspace. For one-on-one messages use clickup_chat_dm instead. Add members later via the channel-members endpoint. Returns the created channel object including its new id.",
1167            "inputSchema": {
1168                "type": "object",
1169                "properties": {
1170                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1171                    "name": {"type": "string", "description": "Channel name (e.g. 'product-launch'). Must be unique within the workspace."},
1172                    "description": {"type": "string", "description": "Optional channel topic/description shown in the header."},
1173                    "visibility": {"type": "string", "description": "Channel visibility: 'public' (any workspace member can join) or 'private' (invite only). Defaults to 'public'."}
1174                },
1175                "required": ["name"]
1176            }
1177        },
1178        {
1179            "name": "clickup_chat_channel_get",
1180            "description": "Fetch metadata for a single ClickUp chat channel — name, description, visibility, member count, latest activity. Does not return the messages themselves; use clickup_chat_message_list for that. Returns the channel object.",
1181            "inputSchema": {
1182                "type": "object",
1183                "properties": {
1184                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."},
1185                    "channel_id": {"type": "string", "description": "ID of the channel to fetch. Obtain from clickup_chat_channel_list (field: id)."}
1186                },
1187                "required": ["channel_id"]
1188            }
1189        },
1190        {
1191            "name": "clickup_chat_channel_update",
1192            "description": "Rename a ClickUp chat channel or change its description. To change membership or visibility use the dedicated channel-members and channel-followers tools. Returns the updated channel object.",
1193            "inputSchema": {
1194                "type": "object",
1195                "properties": {
1196                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."},
1197                    "channel_id": {"type": "string", "description": "ID of the channel to update. Obtain from clickup_chat_channel_list (field: id)."},
1198                    "name": {"type": "string", "description": "New display name for the channel. Must be unique within the workspace."},
1199                    "description": {"type": "string", "description": "New channel description shown in the channel header."}
1200                },
1201                "required": ["channel_id"]
1202            }
1203        },
1204        {
1205            "name": "clickup_chat_channel_delete",
1206            "description": "Permanently delete a ClickUp Chat channel along with every message and reply it contains. Destructive, irreversible, and cascading — confirm with the user before calling. The channel vanishes from the workspace for all members. Returns an empty object on success.",
1207            "inputSchema": {
1208                "type": "object",
1209                "properties": {
1210                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1211                    "channel_id": {"type": "string", "description": "ID of the channel to delete. Obtain from clickup_chat_channel_list (field: id). All messages and replies inside are deleted with it."}
1212                },
1213                "required": ["channel_id"]
1214            }
1215        },
1216        {
1217            "name": "clickup_chat_message_list",
1218            "description": "List messages in a ClickUp Chat channel, newest first. Only top-level messages are returned; use clickup_chat_reply_list for threaded replies. Returns a compact array of message objects. Pass `cursor`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array, with `pagination.next_cursor` to pass back for the previous page.",
1219            "inputSchema": {
1220                "type": "object",
1221                "properties": {
1222                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1223                    "channel_id": {"type": "string", "description": "ID of the channel. Obtain from clickup_chat_channel_list (field: id)."},
1224                    "cursor": {"type": "string", "description": "Opaque pagination cursor from a previous response's `pagination.next_cursor`. Omit for the first page (newest messages)."},
1225                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
1226                    "all": {"type": "boolean", "description": "true = auto-fetch pages until next_cursor is empty or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
1227                },
1228                "required": ["channel_id"]
1229            }
1230        },
1231        {
1232            "name": "clickup_chat_message_send",
1233            "description": "Post a new top-level message to a ClickUp Chat channel. For replies inside a thread use clickup_chat_reply_send; for DMs use clickup_chat_dm. Returns the created message object including its new id, which you can pass to clickup_chat_reaction_add, clickup_chat_reply_send, etc.",
1234            "inputSchema": {
1235                "type": "object",
1236                "properties": {
1237                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1238                    "channel_id": {"type": "string", "description": "ID of the target channel. Obtain from clickup_chat_channel_list (field: id)."},
1239                    "content": {"type": "string", "description": "Message body. Supports markdown, @mentions (e.g. '@username'), and emoji."},
1240                    "type": {"type": "string", "description": "Message subtype. Defaults to 'message' (a normal chat message). Use 'post' for a long-form post. ClickUp requires this field server-side."}
1241                },
1242                "required": ["channel_id", "content"]
1243            }
1244        },
1245        {
1246            "name": "clickup_chat_message_delete",
1247            "description": "Permanently delete a message from a ClickUp chat channel or DM thread. Destructive and irreversible — the message and its threaded replies are removed for all viewers. Only the message author or a workspace admin can delete; other users will get a 403. Returns an empty object on success.",
1248            "inputSchema": {
1249                "type": "object",
1250                "properties": {
1251                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."},
1252                    "message_id": {"type": "string", "description": "ID of the message to delete. Obtain from clickup_chat_message_list (field: id) or clickup_chat_reply_list."}
1253                },
1254                "required": ["message_id"]
1255            }
1256        },
1257        {
1258            "name": "clickup_chat_dm",
1259            "description": "Create or fetch the direct-message channel between the authenticated user and one or more other workspace members (ClickUp groups DMs around the participant set). Returns the channel object including its id. To send a message in the channel, follow with clickup_chat_message_send using the returned channel id.",
1260            "inputSchema": {
1261                "type": "object",
1262                "properties": {
1263                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1264                    "user_ids": {
1265                        "type": "array",
1266                        "items": {"type": "integer"},
1267                        "description": "Numeric user IDs of the DM participants (excluding the caller). ClickUp permits up to 15 participants for a group DM. Obtain IDs from clickup_member_list or clickup_user_get."
1268                    }
1269                },
1270                "required": ["user_ids"]
1271            }
1272        },
1273        {
1274            "name": "clickup_webhook_create",
1275            "description": "Register an HTTPS endpoint that ClickUp will POST events to as things happen in the workspace (tasks created, comments added, status changes, etc.). Optionally scope the webhook to a single space, folder, list, or task. The response includes a 'secret' you should use to verify the X-Signature header on incoming payloads. Returns the created webhook object.",
1276            "inputSchema": {
1277                "type": "object",
1278                "properties": {
1279                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."},
1280                    "endpoint": {"type": "string", "description": "Public HTTPS URL that will receive event POSTs. Must respond 2xx within 5 seconds or ClickUp will retry/suspend."},
1281                    "events": {
1282                        "type": "array",
1283                        "items": {"type": "string"},
1284                        "description": "Event names to subscribe to (e.g. ['taskCreated','taskUpdated','taskStatusUpdated','commentPosted']). Pass ['*'] to subscribe to every event ClickUp emits."
1285                    },
1286                    "space_id": {"type": "string", "description": "Scope events to this space only. Mutually exclusive with folder_id/list_id/task_id."},
1287                    "folder_id": {"type": "string", "description": "Scope events to this folder only. Mutually exclusive with space_id/list_id/task_id."},
1288                    "list_id": {"type": "string", "description": "Scope events to this list only. Mutually exclusive with space_id/folder_id/task_id."},
1289                    "task_id": {"type": "string", "description": "Scope events to this task only. Mutually exclusive with space_id/folder_id/list_id."}
1290                },
1291                "required": ["endpoint", "events"]
1292            }
1293        },
1294        {
1295            "name": "clickup_webhook_update",
1296            "description": "Change the delivery endpoint, subscribed events, or active status of a ClickUp webhook. To temporarily pause deliveries without losing the webhook config, set status='suspended' (then resume later with status='active'). Returns the updated webhook object.",
1297            "inputSchema": {
1298                "type": "object",
1299                "properties": {
1300                    "webhook_id": {"type": "string", "description": "ID of the webhook to update. Obtain from clickup_webhook_list (field: id)."},
1301                    "endpoint": {"type": "string", "description": "New HTTPS URL that ClickUp will POST events to. Must be publicly reachable and respond with 2xx within 5 seconds."},
1302                    "events": {
1303                        "type": "array",
1304                        "items": {"type": "string"},
1305                        "description": "New list of event names to subscribe to (e.g. ['taskCreated','taskUpdated']). Pass ['*'] to subscribe to every event. Omit to leave subscriptions unchanged."
1306                    },
1307                    "status": {"type": "string", "description": "'active' to deliver events; 'suspended' to pause deliveries without deleting the webhook."}
1308                },
1309                "required": ["webhook_id"]
1310            }
1311        },
1312        {
1313            "name": "clickup_webhook_delete",
1314            "description": "Permanently delete a ClickUp webhook, stopping all future event deliveries to its endpoint. Destructive and irreversible: the webhook record is removed immediately. If you only want to pause deliveries, use clickup_webhook_update with status='inactive' instead. Returns an empty object on success.",
1315            "inputSchema": {
1316                "type": "object",
1317                "properties": {
1318                    "webhook_id": {"type": "string", "description": "ID of the webhook to delete. Obtain from clickup_webhook_list (field: id). The authenticated user must own the webhook or be a workspace admin."}
1319                },
1320                "required": ["webhook_id"]
1321            }
1322        },
1323        {
1324            "name": "clickup_checklist_add_item",
1325            "description": "Append a new item to an existing ClickUp checklist on a task. The item starts unresolved. To edit or resolve items use clickup_checklist_update_item; to remove them use clickup_checklist_delete_item. Returns the updated checklist object (with all items).",
1326            "inputSchema": {
1327                "type": "object",
1328                "properties": {
1329                    "checklist_id": {"type": "string", "description": "ID of the parent checklist. Obtain from clickup_task_get (field: checklists[].id)."},
1330                    "name": {"type": "string", "description": "Display text of the new checklist item (e.g. 'Send release notes')."},
1331                    "assignee": {"type": "integer", "description": "Optional user ID to assign this item to (they will see it on their assigned work). Obtain from clickup_member_list."}
1332                },
1333                "required": ["checklist_id", "name"]
1334            }
1335        },
1336        {
1337            "name": "clickup_checklist_update_item",
1338            "description": "Modify a single checklist item on a ClickUp task — rename it, toggle its resolved state, or change its assignee. Use clickup_checklist_add_item to create new items and clickup_checklist_delete_item to remove them. Returns the updated checklist object (all items).",
1339            "inputSchema": {
1340                "type": "object",
1341                "properties": {
1342                    "checklist_id": {"type": "string", "description": "ID of the parent checklist. Obtain from clickup_task_get (field: checklists[].id)."},
1343                    "item_id": {"type": "string", "description": "ID of the item to update. Obtain from clickup_task_get (field: checklists[].items[].id)."},
1344                    "name": {"type": "string", "description": "New text for the item. Omit to keep current text."},
1345                    "resolved": {"type": "boolean", "description": "true = mark as done (strike-through); false = mark as open."},
1346                    "assignee": {"type": "integer", "description": "Reassign the item to this user ID. Obtain user IDs from clickup_member_list or clickup_user_get. Pass no value to leave assignee unchanged."}
1347                },
1348                "required": ["checklist_id", "item_id"]
1349            }
1350        },
1351        {
1352            "name": "clickup_checklist_delete_item",
1353            "description": "Permanently delete a single item from a ClickUp checklist. Destructive and irreversible. To resolve the item (mark done) without deleting, use clickup_checklist_update_item with resolved=true. Returns the updated checklist object (remaining items).",
1354            "inputSchema": {
1355                "type": "object",
1356                "properties": {
1357                    "checklist_id": {"type": "string", "description": "ID of the parent checklist. Obtain from clickup_task_get (field: checklists[].id)."},
1358                    "item_id": {"type": "string", "description": "ID of the item to delete. Obtain from clickup_task_get (field: checklists[].items[].id)."}
1359                },
1360                "required": ["checklist_id", "item_id"]
1361            }
1362        },
1363        {
1364            "name": "clickup_user_get",
1365            "description": "Fetch the profile of a specific member of a ClickUp workspace — username, email, color, profile picture, role. Returns the user object. Use clickup_member_list for task/list members; use clickup_whoami for the authenticated user.",
1366            "inputSchema": {
1367                "type": "object",
1368                "properties": {
1369                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1370                    "user_id": {"type": "integer", "description": "Numeric user ID. Obtain from clickup_member_list or clickup_workspace_list (field: members[].user.id)."}
1371                },
1372                "required": ["user_id"]
1373            }
1374        },
1375        {
1376            "name": "clickup_workspace_seats",
1377            "description": "Get the seat-usage breakdown for a ClickUp workspace — how many paid member seats, guest seats, and internal seats are used vs. available. Useful before inviting new users to confirm capacity. Returns an object with member/guest/internal seat counts.",
1378            "inputSchema": {
1379                "type": "object",
1380                "properties": {
1381                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."}
1382                },
1383                "required": []
1384            }
1385        },
1386        {
1387            "name": "clickup_workspace_plan",
1388            "description": "Get the current subscription plan of a ClickUp workspace (Free, Unlimited, Business, Business Plus, Enterprise), along with plan_name and plan_id. Some features (guests, audit logs, ACLs) require Enterprise. Returns the plan object.",
1389            "inputSchema": {
1390                "type": "object",
1391                "properties": {
1392                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."}
1393                },
1394                "required": []
1395            }
1396        },
1397        {
1398            "name": "clickup_tag_create",
1399            "description": "Define a new tag in a ClickUp space. Tags are space-scoped and must be created before they can be applied to tasks via clickup_task_add_tag. Note: create uses tag_fg/tag_bg, but clickup_tag_update uses fg_color/bg_color (API inconsistency). Returns an empty object on success; use clickup_tag_list to see the created tag.",
1400            "inputSchema": {
1401                "type": "object",
1402                "properties": {
1403                    "space_id": {"type": "string", "description": "ID of the space to create the tag in. Obtain from clickup_space_list (field: id)."},
1404                    "name": {"type": "string", "description": "Tag name (e.g. 'blocked', 'priority'). Must be unique within the space."},
1405                    "tag_fg": {"type": "string", "description": "Text (foreground) hex colour including leading '#' (e.g. '#FFFFFF'). Omit for default."},
1406                    "tag_bg": {"type": "string", "description": "Pill (background) hex colour including leading '#' (e.g. '#FF0000'). Omit for default."}
1407                },
1408                "required": ["space_id", "name"]
1409            }
1410        },
1411        {
1412            "name": "clickup_tag_update",
1413            "description": "Rename a tag or change its colours within a ClickUp space. All tasks using the tag are automatically updated with the new name/colours. Note: update uses fg_color/bg_color whereas tag_create uses tag_fg/tag_bg (API inconsistency). Returns an empty object on success.",
1414            "inputSchema": {
1415                "type": "object",
1416                "properties": {
1417                    "space_id": {"type": "string", "description": "ID of the space containing the tag. Obtain from clickup_space_list (field: id)."},
1418                    "tag_name": {"type": "string", "description": "Current name of the tag to update. Obtain from clickup_tag_list (field: name)."},
1419                    "name": {"type": "string", "description": "New tag name. Omit to keep current name."},
1420                    "tag_fg": {"type": "string", "description": "New text (foreground) hex colour with leading '#'. Note: forwarded as fg_color to the API."},
1421                    "tag_bg": {"type": "string", "description": "New pill (background) hex colour with leading '#'. Note: forwarded as bg_color to the API."}
1422                },
1423                "required": ["space_id", "tag_name"]
1424            }
1425        },
1426        {
1427            "name": "clickup_tag_delete",
1428            "description": "Delete a tag from a ClickUp space. The tag is removed from every task that uses it (the tasks themselves are not affected). Destructive and irreversible. Returns an empty object on success.",
1429            "inputSchema": {
1430                "type": "object",
1431                "properties": {
1432                    "space_id": {"type": "string", "description": "ID of the space containing the tag. Obtain from clickup_space_list (field: id)."},
1433                    "tag_name": {"type": "string", "description": "Name of the tag to delete. Obtain from clickup_tag_list (field: name)."}
1434                },
1435                "required": ["space_id", "tag_name"]
1436            }
1437        },
1438        {
1439            "name": "clickup_field_unset",
1440            "description": "Clear a custom field value on a ClickUp task — sets it back to empty/unset. The field definition on the list remains intact. Use clickup_field_set to assign a new value instead. Returns an empty object on success.",
1441            "inputSchema": {
1442                "type": "object",
1443                "properties": {
1444                    "task_id": {"type": "string", "description": "ID of the task. Obtain from clickup_task_list (field: id)."},
1445                    "field_id": {"type": "string", "description": "ID of the custom field to clear. Obtain from clickup_field_list (field: id) or clickup_task_get (field: custom_fields[].id)."}
1446                },
1447                "required": ["task_id", "field_id"]
1448            }
1449        },
1450        {
1451            "name": "clickup_attachment_list",
1452            "description": "List files attached to a ClickUp task — each attachment's id, title, size, mime type, url, and uploader. Extracts the attachments array from the Get Task response (ClickUp has no dedicated list endpoint). Use clickup_attachment_upload to add a new file. Returns an array of attachment objects.",
1453            "inputSchema": {
1454                "type": "object",
1455                "properties": {
1456                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1457                    "task_id": {"type": "string", "description": "ID of the task whose attachments to list. Obtain from clickup_task_list (field: id)."}
1458                },
1459                "required": ["task_id"]
1460            }
1461        },
1462        {
1463            "name": "clickup_shared_list",
1464            "description": "List every task, list, and folder that has been explicitly shared with the authenticated user from outside their default hierarchy (e.g. items shared by other workspace members). Useful for discovering items you have access to but don't own. Returns an object with shared tasks, lists, and folders arrays.",
1465            "inputSchema": {
1466                "type": "object",
1467                "properties": {
1468                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."}
1469                },
1470                "required": []
1471            }
1472        },
1473        {
1474            "name": "clickup_group_list",
1475            "description": "List user groups (also called 'teams' in the ClickUp UI) in a workspace. A group is a named collection of users that can be @-mentioned or assigned as a unit. Returns an array of group objects (id, name, members).",
1476            "inputSchema": {
1477                "type": "object",
1478                "properties": {
1479                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1480                    "group_ids": {
1481                        "type": "array",
1482                        "items": {"type": "string"},
1483                        "description": "Optional filter to return only these group IDs. Omit to return all groups in the workspace."
1484                    }
1485                },
1486                "required": []
1487            }
1488        },
1489        {
1490            "name": "clickup_group_create",
1491            "description": "Create a new user group ('team' in ClickUp's UI) in a workspace. Groups let you @-mention or assign multiple users as a unit. At least one initial member is required. Returns the created group object including its new id.",
1492            "inputSchema": {
1493                "type": "object",
1494                "properties": {
1495                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1496                    "name": {"type": "string", "description": "Display name for the group (e.g. 'Frontend Engineers')."},
1497                    "member_ids": {
1498                        "type": "array",
1499                        "items": {"type": "integer"},
1500                        "description": "User IDs to add as initial members. Obtain from clickup_member_list or clickup_user_get (field: id)."
1501                    }
1502                },
1503                "required": ["name"]
1504            }
1505        },
1506        {
1507            "name": "clickup_group_update",
1508            "description": "Rename a user group and/or add/remove its members. All changes are applied in one call. Use clickup_group_list first to see current membership. Returns the updated group object.",
1509            "inputSchema": {
1510                "type": "object",
1511                "properties": {
1512                    "group_id": {"type": "string", "description": "ID of the group to update. Obtain from clickup_group_list (field: id)."},
1513                    "name": {"type": "string", "description": "New display name. Omit to keep current name."},
1514                    "add_members": {
1515                        "type": "array",
1516                        "items": {"type": "integer"},
1517                        "description": "User IDs to add to the group (additive — does not replace current members)."
1518                    },
1519                    "rem_members": {
1520                        "type": "array",
1521                        "items": {"type": "integer"},
1522                        "description": "User IDs to remove from the group (no-op if not currently a member)."
1523                    }
1524                },
1525                "required": ["group_id"]
1526            }
1527        },
1528        {
1529            "name": "clickup_group_delete",
1530            "description": "Permanently delete a ClickUp user group. Destructive and irreversible — assignments and mentions that referenced the group remain as historical records, but the group can no longer be used going forward. The individual users are not affected. Returns an empty object on success.",
1531            "inputSchema": {
1532                "type": "object",
1533                "properties": {
1534                    "group_id": {"type": "string", "description": "ID of the group to delete. Obtain from clickup_group_list (field: id)."}
1535                },
1536                "required": ["group_id"]
1537            }
1538        },
1539        {
1540            "name": "clickup_role_list",
1541            "description": "List the custom roles defined in a ClickUp workspace (Member, Guest, Admin, Owner, plus any custom roles on Enterprise plans). Roles define baseline permissions assigned to users. Returns an array of role objects (id, name, members).",
1542            "inputSchema": {
1543                "type": "object",
1544                "properties": {
1545                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."}
1546                },
1547                "required": []
1548            }
1549        },
1550        {
1551            "name": "clickup_guest_get",
1552            "description": "Fetch the profile of a specific guest user in a ClickUp workspace — email, permissions (can_edit_tags, can_see_time_spent, can_create_views), and shared items. Guests are external collaborators with limited access. Requires Enterprise plan. Returns the guest object.",
1553            "inputSchema": {
1554                "type": "object",
1555                "properties": {
1556                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1557                    "guest_id": {"type": "integer", "description": "Numeric guest user ID. Obtain from clickup_guest_invite (returns the new guest) or the guest's entry in a shared-item's members list."}
1558                },
1559                "required": ["guest_id"]
1560            }
1561        },
1562        {
1563            "name": "clickup_task_time_in_status",
1564            "description": "Report how long a task has spent in each status since creation (e.g. 3 days in 'open', 1 day in 'in review'). Useful for cycle-time analysis. Returns an object mapping status names to total-time and since-timestamp values (all times in milliseconds).",
1565            "inputSchema": {
1566                "type": "object",
1567                "properties": {
1568                    "task_id": {"type": "string", "description": "ID of the task. Obtain from clickup_task_list (field: id) or clickup_task_search."}
1569                },
1570                "required": ["task_id"]
1571            }
1572        },
1573        {
1574            "name": "clickup_task_move",
1575            "description": "Move a task to a different list (change home list)",
1576            "inputSchema": {
1577                "type": "object",
1578                "properties": {
1579                    "task_id": {"type": "string", "description": "Task ID"},
1580                    "list_id": {"type": "string", "description": "Destination list ID"},
1581                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."}
1582                },
1583                "required": ["task_id", "list_id"]
1584            }
1585        },
1586        {
1587            "name": "clickup_task_set_estimate",
1588            "description": "Set a time estimate on a ClickUp task. If user_id is provided, sets a per-user estimate (additive, Business plan+). If user_id is omitted, sets the total task-level estimate (compatible with all plans). Estimates are in milliseconds.",
1589            "inputSchema": {
1590                "type": "object",
1591                "properties": {
1592                    "task_id": {"type": "string", "description": "ID of the task. Obtain from clickup_task_list (field: id)."},
1593                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1594                    "user_id": {"type": "integer", "description": "Numeric ID of the user whose estimate to set. Omit to set task-level estimate."},
1595                    "time_estimate": {"type": "integer", "description": "Estimated effort in milliseconds (e.g. 3600000 = 1 hour, 28800000 = 8 hours)."}
1596                },
1597                "required": ["task_id", "time_estimate"]
1598            }
1599        },
1600        {
1601            "name": "clickup_task_replace_estimates",
1602            "description": "Replace the full set of per-user time estimates on a task. The request body is an array; any user not in the array has their estimate removed. To set one user's estimate without disturbing others, use clickup_task_set_estimate instead. Body shape per ClickUp's spec: [{assignee, time}]. Requires Business plan for multiple owners.",
1603            "inputSchema": {
1604                "type": "object",
1605                "properties": {
1606                    "task_id": {"type": "string", "description": "Task ID. Custom task IDs (PROJ-42) are auto-detected."},
1607                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."},
1608                    "estimates": {
1609                        "type": "array",
1610                        "description": "Full set of per-user estimates to replace with. Every assignee not present here will have their estimate removed. At least one entry required.",
1611                        "items": {
1612                            "type": "object",
1613                            "properties": {
1614                                "assignee": {"description": "User ID (integer) or the literal string 'unassigned'."},
1615                                "time": {"type": "integer", "description": "Time estimate in milliseconds (>= 0)."}
1616                            },
1617                            "required": ["assignee", "time"]
1618                        }
1619                    }
1620                },
1621                "required": ["task_id", "estimates"]
1622            }
1623        },
1624        {
1625            "name": "clickup_auth_check",
1626            "description": "Verify that the configured ClickUp API token is valid by hitting the /user endpoint. Returns an ok:true result if the token is accepted, or an error if it's missing, malformed, expired, or revoked. Use clickup_whoami instead to also get the authenticated user's profile.",
1627            "inputSchema": {
1628                "type": "object",
1629                "properties": {},
1630                "required": []
1631            }
1632        },
1633        {
1634            "name": "clickup_checklist_update",
1635            "description": "Rename a checklist or change its position among the task's checklists. Does not affect the checklist's items — use clickup_checklist_update_item / add_item / delete_item for those. Returns the updated checklist object.",
1636            "inputSchema": {
1637                "type": "object",
1638                "properties": {
1639                    "checklist_id": {"type": "string", "description": "ID of the checklist to update. Obtain from clickup_task_get (field: checklists[].id)."},
1640                    "name": {"type": "string", "description": "New display name for the checklist. Omit to keep current name."},
1641                    "position": {"type": "integer", "description": "Zero-indexed position among the task's checklists (0 = first). Omit to keep current position."}
1642                },
1643                "required": ["checklist_id"]
1644            }
1645        },
1646        {
1647            "name": "clickup_comment_replies",
1648            "description": "List the threaded replies attached to a top-level ClickUp comment, newest first. Returns a compact array of reply objects (id, comment_text, user, date). Pass `start`/`start_id`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. Use clickup_comment_reply to post a new reply to the thread.",
1649            "inputSchema": {
1650                "type": "object",
1651                "properties": {
1652                    "comment_id": {"type": "string", "description": "ID of the parent comment. Obtain from clickup_comment_list (field: id)."},
1653                    "start": {"type": "integer", "description": "Unix millisecond timestamp of the boundary reply — pass the previous response's `pagination.next_start`. Required as a pair with `start_id`. Omit for the first page."},
1654                    "start_id": {"type": "string", "description": "Reply ID matching the `start` timestamp — pass the previous response's `pagination.next_start_id`. Required as a pair with `start`. Omit for the first page."},
1655                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
1656                    "all": {"type": "boolean", "description": "true = auto-fetch pages until the server returns a short page (< 25 items) or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
1657                },
1658                "required": ["comment_id"]
1659            }
1660        },
1661        {
1662            "name": "clickup_comment_reply",
1663            "description": "Post a threaded reply under an existing ClickUp comment. Replies appear indented beneath the parent comment. Returns the created reply object including its new id. For a top-level comment, use clickup_comment_create instead.",
1664            "inputSchema": {
1665                "type": "object",
1666                "properties": {
1667                    "comment_id": {"type": "string", "description": "ID of the parent comment to reply to. Obtain from clickup_comment_list (field: id)."},
1668                    "text": {"type": "string", "description": "Reply body. @mentions are rendered. Markdown is NOT rendered by ClickUp's v2 comment API; markdown syntax is stored as literal text."},
1669                    "assignee": {"type": "integer", "description": "Optional user ID to assign the reply to — they receive a notification. Obtain from clickup_member_list."}
1670                },
1671                "required": ["comment_id", "text"]
1672            }
1673        },
1674        {
1675            "name": "clickup_chat_channel_list",
1676            "description": "List all ClickUp Chat channels in a workspace that the authenticated user can see. Returns a compact array of channel objects (id, name, type). Pass `cursor`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. Use clickup_chat_channel_create to create new channels.",
1677            "inputSchema": {
1678                "type": "object",
1679                "properties": {
1680                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1681                    "include_closed": {"type": "boolean", "description": "true = include archived/closed channels in the result; false or omitted = only active channels."},
1682                    "cursor": {"type": "string", "description": "Opaque pagination cursor from a previous response's `pagination.next_cursor`. Omit for the first page."},
1683                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
1684                    "all": {"type": "boolean", "description": "true = auto-fetch pages until next_cursor is empty or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
1685                },
1686                "required": []
1687            }
1688        },
1689        {
1690            "name": "clickup_chat_channel_followers",
1691            "description": "List the users who follow (receive notifications from) a ClickUp Chat channel. Followers are a subset of members — a member may or may not be a follower. Returns a compact array of user objects (id, name, username, email). Pass `cursor`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array.",
1692            "inputSchema": {
1693                "type": "object",
1694                "properties": {
1695                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1696                    "channel_id": {"type": "string", "description": "ID of the channel. Obtain from clickup_chat_channel_list (field: id)."},
1697                    "cursor": {"type": "string", "description": "Opaque pagination cursor from a previous response's `pagination.next_cursor`. Omit for the first page."},
1698                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
1699                    "all": {"type": "boolean", "description": "true = auto-fetch pages until next_cursor is empty or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
1700                },
1701                "required": ["channel_id"]
1702            }
1703        },
1704        {
1705            "name": "clickup_chat_channel_members",
1706            "description": "List the users who are members of a ClickUp Chat channel (can read and post). For notification-receivers only use clickup_chat_channel_followers. Returns a compact array of user objects (id, name, username, email). Pass `cursor`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array.",
1707            "inputSchema": {
1708                "type": "object",
1709                "properties": {
1710                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1711                    "channel_id": {"type": "string", "description": "ID of the channel. Obtain from clickup_chat_channel_list (field: id)."},
1712                    "cursor": {"type": "string", "description": "Opaque pagination cursor from a previous response's `pagination.next_cursor`. Omit for the first page."},
1713                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
1714                    "all": {"type": "boolean", "description": "true = auto-fetch pages until next_cursor is empty or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
1715                },
1716                "required": ["channel_id"]
1717            }
1718        },
1719        {
1720            "name": "clickup_chat_message_update",
1721            "description": "Edit the body of an existing ClickUp Chat message. Only the author (or a workspace admin) can edit a message; others will get a 403. The supplied text replaces the existing body entirely. Returns the updated message object.",
1722            "inputSchema": {
1723                "type": "object",
1724                "properties": {
1725                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1726                    "message_id": {"type": "string", "description": "ID of the message to edit. Obtain from clickup_chat_message_list (field: id) or clickup_chat_reply_list."},
1727                    "text": {"type": "string", "description": "Replacement body for the message. Markdown, emoji, and @mentions supported. Overwrites the existing body entirely."}
1728                },
1729                "required": ["message_id", "text"]
1730            }
1731        },
1732        {
1733            "name": "clickup_chat_reaction_list",
1734            "description": "List the emoji reactions on a ClickUp Chat message — each entry carries the reaction (emoji), the user who reacted, and the timestamp. Returns a compact array (reaction, user, date). Pass `cursor`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array.",
1735            "inputSchema": {
1736                "type": "object",
1737                "properties": {
1738                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1739                    "message_id": {"type": "string", "description": "ID of the message whose reactions to list. Obtain from clickup_chat_message_list (field: id)."},
1740                    "cursor": {"type": "string", "description": "Opaque pagination cursor from a previous response's `pagination.next_cursor`. Omit for the first page."},
1741                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
1742                    "all": {"type": "boolean", "description": "true = auto-fetch pages until next_cursor is empty or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
1743                },
1744                "required": ["message_id"]
1745            }
1746        },
1747        {
1748            "name": "clickup_chat_reaction_add",
1749            "description": "Add an emoji reaction from the authenticated user to a ClickUp Chat message. If the user has already reacted with the same emoji, the call is a no-op. Returns an empty object on success.",
1750            "inputSchema": {
1751                "type": "object",
1752                "properties": {
1753                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1754                    "message_id": {"type": "string", "description": "ID of the message to react to. Obtain from clickup_chat_message_list (field: id) or clickup_chat_reply_list."},
1755                    "emoji": {"type": "string", "description": "Unicode emoji character to add (e.g. '👍', '🎉', '❤️'). Custom Slack-style shortcodes (':+1:') are not supported — use the raw emoji character."}
1756                },
1757                "required": ["message_id", "emoji"]
1758            }
1759        },
1760        {
1761            "name": "clickup_chat_reaction_remove",
1762            "description": "Remove the authenticated user's emoji reaction from a ClickUp Chat message. Only removes your own reaction — other users' reactions of the same emoji are preserved. No-op if you haven't reacted with the given emoji. Returns an empty object on success.",
1763            "inputSchema": {
1764                "type": "object",
1765                "properties": {
1766                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1767                    "message_id": {"type": "string", "description": "ID of the message. Obtain from clickup_chat_message_list (field: id)."},
1768                    "emoji": {"type": "string", "description": "The Unicode emoji character to remove (e.g. '👍'). Must match the exact emoji you reacted with."}
1769                },
1770                "required": ["message_id", "emoji"]
1771            }
1772        },
1773        {
1774            "name": "clickup_chat_reply_list",
1775            "description": "List the threaded replies attached to a top-level ClickUp Chat message, oldest first. Returns a compact array of reply objects. Pass `cursor`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. Use clickup_chat_reply_send to post a new reply.",
1776            "inputSchema": {
1777                "type": "object",
1778                "properties": {
1779                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1780                    "message_id": {"type": "string", "description": "ID of the parent message. Obtain from clickup_chat_message_list (field: id)."},
1781                    "cursor": {"type": "string", "description": "Opaque pagination cursor from a previous response's `pagination.next_cursor`. Omit for the first page."},
1782                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
1783                    "all": {"type": "boolean", "description": "true = auto-fetch pages until next_cursor is empty or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
1784                },
1785                "required": ["message_id"]
1786            }
1787        },
1788        {
1789            "name": "clickup_chat_reply_send",
1790            "description": "Post a threaded reply beneath an existing ClickUp Chat message. The reply appears in the message's thread panel. Returns the created reply object. Use clickup_chat_message_send for new top-level messages.",
1791            "inputSchema": {
1792                "type": "object",
1793                "properties": {
1794                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1795                    "message_id": {"type": "string", "description": "ID of the parent message to reply to. Obtain from clickup_chat_message_list (field: id)."},
1796                    "text": {"type": "string", "description": "Reply body. Markdown, emoji, and @mentions supported."}
1797                },
1798                "required": ["message_id", "text"]
1799            }
1800        },
1801        {
1802            "name": "clickup_chat_tagged_users",
1803            "description": "List the users explicitly @-mentioned (tagged) in a ClickUp Chat message body. Useful for reading who a message was addressed to. Returns a compact array of user objects (id, name, username, email). Pass `cursor`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array.",
1804            "inputSchema": {
1805                "type": "object",
1806                "properties": {
1807                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1808                    "message_id": {"type": "string", "description": "ID of the message. Obtain from clickup_chat_message_list (field: id)."},
1809                    "cursor": {"type": "string", "description": "Opaque pagination cursor from a previous response's `pagination.next_cursor`. Omit for the first page."},
1810                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
1811                    "all": {"type": "boolean", "description": "true = auto-fetch pages until next_cursor is empty or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
1812                },
1813                "required": ["message_id"]
1814            }
1815        },
1816        {
1817            "name": "clickup_time_current",
1818            "description": "Get the currently running time tracking entry",
1819            "inputSchema": {
1820                "type": "object",
1821                "properties": {
1822                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."}
1823                },
1824                "required": []
1825            }
1826        },
1827        {
1828            "name": "clickup_time_tags",
1829            "description": "List all time entry tags for a workspace",
1830            "inputSchema": {
1831                "type": "object",
1832                "properties": {
1833                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."}
1834                },
1835                "required": []
1836            }
1837        },
1838        {
1839            "name": "clickup_time_add_tags",
1840            "description": "Apply one or more tags to one or more time tracking entries in a single call. Tags are created automatically if they don't yet exist in the workspace's time-entry tag set. Use clickup_time_tags to list existing tags. Returns an empty object on success.",
1841            "inputSchema": {
1842                "type": "object",
1843                "properties": {
1844                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1845                    "entry_ids": {
1846                        "type": "array",
1847                        "items": {"type": "string"},
1848                        "description": "IDs of the time entries to tag. Obtain from clickup_time_list (field: id)."
1849                    },
1850                    "tag_names": {
1851                        "type": "array",
1852                        "items": {"type": "string"},
1853                        "description": "Tag names to apply. Created if they don't exist in the workspace's tag set."
1854                    }
1855                },
1856                "required": ["entry_ids", "tag_names"]
1857            }
1858        },
1859        {
1860            "name": "clickup_time_remove_tags",
1861            "description": "Detach one or more tags from one or more time tracking entries in a single call. The tag definitions themselves remain in the workspace. No-op for entries not currently carrying the tag. Returns an empty object on success.",
1862            "inputSchema": {
1863                "type": "object",
1864                "properties": {
1865                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1866                    "entry_ids": {
1867                        "type": "array",
1868                        "items": {"type": "string"},
1869                        "description": "IDs of the time entries to untag. Obtain from clickup_time_list (field: id)."
1870                    },
1871                    "tag_names": {
1872                        "type": "array",
1873                        "items": {"type": "string"},
1874                        "description": "Tag names to remove. Obtain from clickup_time_tags (field: name)."
1875                    }
1876                },
1877                "required": ["entry_ids", "tag_names"]
1878            }
1879        },
1880        {
1881            "name": "clickup_time_rename_tag",
1882            "description": "Rename a time-entry tag across the entire workspace. All historical time entries carrying the old name are updated. ClickUp's spec requires the new background and foreground hex colours on every rename call (pass the existing values if you don't want to change them). Returns an empty object on success.",
1883            "inputSchema": {
1884                "type": "object",
1885                "properties": {
1886                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1887                    "name": {"type": "string", "description": "Current name of the tag to rename. Obtain from clickup_time_tags (field: name)."},
1888                    "new_name": {"type": "string", "description": "Replacement name for the tag. Must not collide with an existing time-entry tag."},
1889                    "tag_bg": {"type": "string", "description": "Required. New background colour as a hex string (e.g. #000000). Pass the existing value to leave the colour unchanged."},
1890                    "tag_fg": {"type": "string", "description": "Required. New foreground colour as a hex string (e.g. #FFFFFF). Pass the existing value to leave the colour unchanged."}
1891                },
1892                "required": ["name", "new_name", "tag_bg", "tag_fg"]
1893            }
1894        },
1895        {
1896            "name": "clickup_time_history",
1897            "description": "Fetch the audit history of edits made to a time tracking entry — every start/duration/description/billable change, the user who made it, and when. Useful for auditing. Returns an array of history event objects.",
1898            "inputSchema": {
1899                "type": "object",
1900                "properties": {
1901                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1902                    "timer_id": {"type": "string", "description": "ID of the time entry. Obtain from clickup_time_list (field: id)."}
1903                },
1904                "required": ["timer_id"]
1905            }
1906        },
1907        {
1908            "name": "clickup_guest_invite",
1909            "description": "Invite a new external guest user to a ClickUp workspace by email. Guests have limited access and don't consume paid member seats (they use guest seats). The invitation email is sent automatically; the guest must accept before they can log in. Share specific items with them via clickup_guest_share_task / _share_list / _share_folder. Requires Enterprise plan. Returns the created guest object including its new id.",
1910            "inputSchema": {
1911                "type": "object",
1912                "properties": {
1913                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1914                    "email": {"type": "string", "description": "Email address to send the invitation to. Must be a valid email that isn't already a member or guest of the workspace."},
1915                    "can_edit_tags": {"type": "boolean", "description": "true = allow the guest to create/rename/delete tags on items shared with them; false or omitted = tag management denied."},
1916                    "can_see_time_spent": {"type": "boolean", "description": "true = allow the guest to see time-tracking data on shared tasks; false or omitted = hidden."},
1917                    "can_create_views": {"type": "boolean", "description": "true = allow the guest to create their own saved views on shared items; false or omitted = cannot create views."}
1918                },
1919                "required": ["email"]
1920            }
1921        },
1922        {
1923            "name": "clickup_guest_update",
1924            "description": "Update a ClickUp guest's workspace-wide capability flags (edit tags, see time spent, create views). Does not change which items are shared with them — use clickup_guest_share_* / _unshare_* for that. Requires Enterprise plan. Returns the updated guest object.",
1925            "inputSchema": {
1926                "type": "object",
1927                "properties": {
1928                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1929                    "guest_id": {"type": "integer", "description": "Numeric guest user ID. Obtain from clickup_guest_get or from clickup_guest_invite (response.id)."},
1930                    "can_edit_tags": {"type": "boolean", "description": "true = allow the guest to manage tags on shared items; false = deny. Omit to keep current value."},
1931                    "can_see_time_spent": {"type": "boolean", "description": "true = guest can see time-tracking on shared tasks; false = hidden. Omit to keep current value."},
1932                    "can_create_views": {"type": "boolean", "description": "true = guest can create saved views; false = cannot. Omit to keep current value."}
1933                },
1934                "required": ["guest_id"]
1935            }
1936        },
1937        {
1938            "name": "clickup_guest_remove",
1939            "description": "Permanently revoke a guest user's access to a ClickUp workspace. All share-records for the guest are deleted and they can no longer log in. Destructive and irreversible — to re-invite, use clickup_guest_invite (a new guest_id will be assigned). Requires Enterprise plan. Returns an empty object on success.",
1940            "inputSchema": {
1941                "type": "object",
1942                "properties": {
1943                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
1944                    "guest_id": {"type": "integer", "description": "Numeric guest user ID to remove. Obtain from clickup_guest_get or clickup_guest_invite. All their shared-item access is revoked."}
1945                },
1946                "required": ["guest_id"]
1947            }
1948        },
1949        {
1950            "name": "clickup_guest_share_task",
1951            "description": "Grant a ClickUp guest user access to a single task at a specified permission level. Scopes strictly to that task — subtasks and the parent list are not shared. Use clickup_guest_unshare_task to revoke. Requires Enterprise plan. Returns the updated guest object.",
1952            "inputSchema": {
1953                "type": "object",
1954                "properties": {
1955                    "task_id": {"type": "string", "description": "ID of the task to share. Obtain from clickup_task_list (field: id) or clickup_task_search."},
1956                    "guest_id": {"type": "integer", "description": "Numeric ID of the guest user. Obtain from clickup_guest_get or clickup_guest_invite (response.id)."},
1957                    "permission": {"type": "string", "description": "Access level: 'read' (view only), 'comment' (view + comment), 'create' (comment + create subtasks), 'edit' (full edit rights on this task)."}
1958                },
1959                "required": ["task_id", "guest_id", "permission"]
1960            }
1961        },
1962        {
1963            "name": "clickup_guest_unshare_task",
1964            "description": "Revoke a guest's access to a task",
1965            "inputSchema": {
1966                "type": "object",
1967                "properties": {
1968                    "task_id": {"type": "string", "description": "Task ID"},
1969                    "guest_id": {"type": "integer", "description": "Guest user ID"}
1970                },
1971                "required": ["task_id", "guest_id"]
1972            }
1973        },
1974        {
1975            "name": "clickup_guest_share_list",
1976            "description": "Grant a ClickUp guest user access to a specific list at a chosen permission level. Guests are external collaborators (not paid workspace seats); this is how you scope what a guest can see/do. To revoke access later use clickup_guest_unshare_list. Requires Enterprise plan. Returns the updated guest object.",
1977            "inputSchema": {
1978                "type": "object",
1979                "properties": {
1980                    "list_id": {"type": "string", "description": "ID of the list to share. Obtain from clickup_list_list (field: id)."},
1981                    "guest_id": {"type": "integer", "description": "Numeric ID of the guest user. Obtain from clickup_guest_get or the response of clickup_guest_invite."},
1982                    "permission": {"type": "string", "description": "Access level: 'read' (view only), 'comment' (view + comment), 'create' (comment + create tasks), 'edit' (full edit rights on existing items)."}
1983                },
1984                "required": ["list_id", "guest_id", "permission"]
1985            }
1986        },
1987        {
1988            "name": "clickup_guest_unshare_list",
1989            "description": "Revoke a guest user's access to a specific list. The guest keeps any separate task-level or folder-level grants they may also have. Destructive in that the guest immediately loses access, but the guest account itself remains — re-share with clickup_guest_share_list. Requires Enterprise plan. Returns the updated guest object.",
1990            "inputSchema": {
1991                "type": "object",
1992                "properties": {
1993                    "list_id": {"type": "string", "description": "ID of the list whose access to revoke. Obtain from clickup_list_list (field: id)."},
1994                    "guest_id": {"type": "integer", "description": "Numeric guest user ID. Obtain from clickup_guest_get or clickup_guest_invite."}
1995                },
1996                "required": ["list_id", "guest_id"]
1997            }
1998        },
1999        {
2000            "name": "clickup_guest_share_folder",
2001            "description": "Grant a ClickUp guest user access to an entire folder — including all its lists and tasks — at a specified permission level. Use clickup_guest_share_list or _share_task for narrower scope. Use clickup_guest_unshare_folder to revoke. Requires Enterprise plan. Returns the updated guest object.",
2002            "inputSchema": {
2003                "type": "object",
2004                "properties": {
2005                    "folder_id": {"type": "string", "description": "ID of the folder to share. Obtain from clickup_folder_list (field: id). All descendant lists and tasks are accessible via this grant."},
2006                    "guest_id": {"type": "integer", "description": "Numeric ID of the guest user. Obtain from clickup_guest_get or clickup_guest_invite (response.id)."},
2007                    "permission": {"type": "string", "description": "Access level applied to every descendant: 'read' (view only), 'comment' (view + comment), 'create' (comment + create tasks), 'edit' (full edit rights)."}
2008                },
2009                "required": ["folder_id", "guest_id", "permission"]
2010            }
2011        },
2012        {
2013            "name": "clickup_guest_unshare_folder",
2014            "description": "Revoke a guest user's access to a folder (and, cascading, to every list and task under it granted via the folder). Separate list-level or task-level grants are preserved. Re-share later with clickup_guest_share_folder. Requires Enterprise plan. Returns the updated guest object.",
2015            "inputSchema": {
2016                "type": "object",
2017                "properties": {
2018                    "folder_id": {"type": "string", "description": "ID of the folder whose access to revoke. Obtain from clickup_folder_list (field: id)."},
2019                    "guest_id": {"type": "integer", "description": "Numeric guest user ID. Obtain from clickup_guest_get or clickup_guest_invite."}
2020                },
2021                "required": ["folder_id", "guest_id"]
2022            }
2023        },
2024        {
2025            "name": "clickup_user_invite",
2026            "description": "Invite a new paid member to a ClickUp workspace by email. Consumes a member seat (see clickup_workspace_seats for availability). For external collaborators who shouldn't have full access, use clickup_guest_invite instead. Returns the created user object.",
2027            "inputSchema": {
2028                "type": "object",
2029                "properties": {
2030                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
2031                    "email": {"type": "string", "description": "Email address to send the invitation to. Must be a valid email not already a member or guest of the workspace."},
2032                    "admin": {"type": "boolean", "description": "true = grant the Admin role (can manage settings, billing, users); false or omitted = standard Member role."}
2033                },
2034                "required": ["email"]
2035            }
2036        },
2037        {
2038            "name": "clickup_user_update",
2039            "description": "Update a ClickUp workspace member's username and/or admin role. Only the authenticated user (if self) or a workspace admin can call this. To change per-item permissions use role-based or share endpoints instead. Returns the updated user object.",
2040            "inputSchema": {
2041                "type": "object",
2042                "properties": {
2043                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
2044                    "user_id": {"type": "integer", "description": "Numeric user ID to update. Obtain from clickup_member_list or clickup_user_get (field: id)."},
2045                    "username": {"type": "string", "description": "New display name. Omit to keep current username."},
2046                    "admin": {"type": "boolean", "description": "true = grant Admin role, false = revoke Admin (revert to Member). Omit to keep current role."}
2047                },
2048                "required": ["user_id"]
2049            }
2050        },
2051        {
2052            "name": "clickup_user_remove",
2053            "description": "Remove a member from a ClickUp workspace, freeing their paid seat. Destructive — their assignments and comments are preserved as historical records but they lose access immediately. To re-add, use clickup_user_invite (a new invitation will be sent). Returns an empty object on success.",
2054            "inputSchema": {
2055                "type": "object",
2056                "properties": {
2057                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
2058                    "user_id": {"type": "integer", "description": "Numeric user ID to remove. Obtain from clickup_member_list (field: id). Cannot remove the workspace Owner."}
2059                },
2060                "required": ["user_id"]
2061            }
2062        },
2063        {
2064            "name": "clickup_template_apply_task",
2065            "description": "Create a new task in a list by instantiating a saved task template. The new task inherits the template's description, checklists, subtasks, custom fields, etc., but uses the supplied name. Use clickup_template_list to discover templates. Returns the created task object.",
2066            "inputSchema": {
2067                "type": "object",
2068                "properties": {
2069                    "list_id": {"type": "string", "description": "ID of the list to create the task in. Obtain from clickup_list_list (field: id)."},
2070                    "template_id": {"type": "string", "description": "ID of the task template to instantiate. Obtain from clickup_template_list (field: id)."},
2071                    "name": {"type": "string", "description": "Name for the newly-created task. Overrides the template's default name."}
2072                },
2073                "required": ["list_id", "template_id", "name"]
2074            }
2075        },
2076        {
2077            "name": "clickup_template_apply_list",
2078            "description": "Create a list from a list template in a folder or space",
2079            "inputSchema": {
2080                "type": "object",
2081                "properties": {
2082                    "template_id": {"type": "string", "description": "Template ID"},
2083                    "name": {"type": "string", "description": "New list name"},
2084                    "folder_id": {"type": "string", "description": "Folder ID (mutually exclusive with space_id)"},
2085                    "space_id": {"type": "string", "description": "Space ID (mutually exclusive with folder_id)"}
2086                },
2087                "required": ["template_id", "name"]
2088            }
2089        },
2090        {
2091            "name": "clickup_template_apply_folder",
2092            "description": "Create a new folder in a space by instantiating a saved folder template. The new folder inherits the template's list structure, statuses, default fields, and other presets, using the supplied name. Use clickup_template_list to discover templates. Returns the created folder object.",
2093            "inputSchema": {
2094                "type": "object",
2095                "properties": {
2096                    "space_id": {"type": "string", "description": "ID of the parent space. Obtain from clickup_space_list (field: id)."},
2097                    "template_id": {"type": "string", "description": "ID of the folder template to instantiate. Obtain from clickup_template_list (field: id)."},
2098                    "name": {"type": "string", "description": "Name for the newly-created folder. Must be unique within the parent space."}
2099                },
2100                "required": ["space_id", "template_id", "name"]
2101            }
2102        },
2103        {
2104            "name": "clickup_attachment_upload",
2105            "description": "Upload a local file as an attachment on a ClickUp task. The file is read from disk, posted as multipart/form-data, and stored on ClickUp's CDN. Use clickup_attachment_list to see attachments afterward. Returns the created attachment object (id, title, size, url).",
2106            "inputSchema": {
2107                "type": "object",
2108                "properties": {
2109                    "task_id": {"type": "string", "description": "ID of the task to attach the file to. Obtain from clickup_task_list (field: id)."},
2110                    "file_path": {"type": "string", "description": "Absolute path to a readable file on the server running this MCP. The filename (basename) is used as the attachment title; size limits apply per workspace plan."}
2111                },
2112                "required": ["task_id", "file_path"]
2113            }
2114        },
2115        {
2116            "name": "clickup_task_type_list",
2117            "description": "List the custom task types (ClickUp 'Custom Items' — e.g. Bug, Epic, Feature) defined at the workspace level. Each has an id, name, and icon and can be chosen when creating tasks. Returns an array of custom item type objects.",
2118            "inputSchema": {
2119                "type": "object",
2120                "properties": {
2121                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."}
2122                },
2123                "required": []
2124            }
2125        },
2126        {
2127            "name": "clickup_doc_get_page",
2128            "description": "Fetch a single page from a ClickUp doc including its full markdown content, title, subtitle, and parent-page link. Use clickup_doc_pages to list all pages in a doc first. Returns the page object with content.",
2129            "inputSchema": {
2130                "type": "object",
2131                "properties": {
2132                    "team_id": {"type": "string", "description": "Workspace (team) ID. Omit to use the default workspace from config."},
2133                    "doc_id": {"type": "string", "description": "ID of the parent doc. Obtain from clickup_doc_list (field: id)."},
2134                    "page_id": {"type": "string", "description": "ID of the page to fetch. Obtain from clickup_doc_pages (field: id)."}
2135                },
2136                "required": ["doc_id", "page_id"]
2137            }
2138        },
2139        {
2140            "name": "clickup_audit_log_query",
2141            "description": "Query the ClickUp audit log (who did what, when) for a workspace. Requires Enterprise plan. Uses body-based pagination — pagination state lives inside the POST body. Returns a compact array of event objects (id, eventType, eventStatus, userId, eventTime). Pass `page_rows`/`page_timestamp`/`page_direction`/`limit`/`all` to paginate — when any pagination arg is provided, the response becomes `{items, pagination}` instead of a bare array. With `all=true` the helper walks pages in the chosen direction (default NEXT) until the server returns an empty page or limit is reached.",
2142            "inputSchema": {
2143                "type": "object",
2144                "properties": {
2145                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
2146                    "applicability": {"type": "string", "description": "Required. Scope of the query. ClickUp's documented values: WORKSPACE, TEAMS, USERS."},
2147                    "event_type": {"type": "string", "description": "Optional filter on event category. ClickUp's documented categories include AUTH, HIERARCHY, USER, CUSTOM_FIELDS, AGENT, OTHER. Maps to filter.eventType."},
2148                    "event_status": {"type": "string", "description": "Optional filter on event status (e.g. SUCCESS, FAILURE). Maps to filter.eventStatus."},
2149                    "user_id": {
2150                        "type": "array",
2151                        "items": {"type": "string"},
2152                        "description": "Optional list of user IDs to filter on. Maps to filter.userId."
2153                    },
2154                    "user_email": {
2155                        "type": "array",
2156                        "items": {"type": "string"},
2157                        "description": "Optional list of user emails to filter on. Maps to filter.userEmail."
2158                    },
2159                    "start_time": {"type": "integer", "description": "Inclusive lower bound as a Unix timestamp in milliseconds. Maps to filter.startTime."},
2160                    "end_time": {"type": "integer", "description": "Inclusive upper bound as a Unix timestamp in milliseconds. Maps to filter.endTime."},
2161                    "page_rows": {"type": "integer", "minimum": 1, "description": "Pagination page size. Maps to pagination.pageRows."},
2162                    "page_timestamp": {"type": "integer", "description": "Boundary timestamp (Unix ms) — pass the previous response's `pagination.next_page_timestamp` to continue. Maps to pagination.pageTimestamp. Omit for the first page."},
2163                    "page_direction": {"type": "string", "enum": ["NEXT", "PREVIOUS"], "description": "Direction to walk relative to `page_timestamp`: NEXT for newer events, PREVIOUS for older. Maps to pagination.pageDirection."},
2164                    "limit": {"type": "integer", "minimum": 1, "description": "Cap total items returned. With all=true this caps across pages; otherwise it caps the single page."},
2165                    "all": {"type": "boolean", "description": "true = auto-fetch pages in the chosen direction until the server returns an empty page or limit is reached (hard cap 100 pages); false or omitted = fetch one page only."}
2166                },
2167                "required": ["applicability"]
2168            }
2169        },
2170        {
2171            "name": "clickup_acl_update",
2172            "description": "Change the privacy (ACL) of a ClickUp hierarchy object — toggle private/public and grant or revoke per-user/per-group access. Uses the v3 ACL endpoint. Requires Enterprise plan. Body shape per ClickUp's OpenAPI spec: { private?: bool, entries?: [{kind, id, permission_level?}] }.",
2173            "inputSchema": {
2174                "type": "object",
2175                "properties": {
2176                    "team_id": {"type": "string", "description": "Workspace (team) ID. Obtain from clickup_workspace_list (field: id). Omit to use the default workspace from config."},
2177                    "object_type": {"type": "string", "description": "Type of object to change: 'space', 'folder', or 'list'."},
2178                    "object_id": {"type": "string", "description": "ID of the space/folder/list. Obtain from the matching list endpoint (clickup_space_list, clickup_folder_list, or clickup_list_list)."},
2179                    "private": {"type": "boolean", "description": "true = make the object private (only explicit members see it); false = make it public (visible to the whole workspace). Omit to leave unchanged."},
2180                    "entries": {
2181                        "type": "array",
2182                        "description": "Grant or revoke per-principal access. Each entry: {kind: 'user'|'group', id: string, permission_level?: integer}. permission_level enum: 1=read, 3=comment, 4=edit, 5=create; pass 0 to revoke. Maps directly to ClickUp's `entries` array per the v3 spec.",
2183                        "items": {
2184                            "type": "object",
2185                            "properties": {
2186                                "kind": {"type": "string", "enum": ["user", "group"], "description": "Principal type."},
2187                                "id": {"type": "string", "description": "User ID (for kind='user') or user-group ID (for kind='group')."},
2188                                "permission_level": {"type": "integer", "description": "1=read, 3=comment, 4=edit, 5=create. Pass 0 to revoke. Defaults to read (1) if omitted on a grant."}
2189                            },
2190                            "required": ["kind", "id"]
2191                        }
2192                    }
2193                },
2194                "required": ["object_type", "object_id"]
2195            }
2196        }
2197    ])
2198}
2199
2200/// Returns `tool_list()` with any tool the filter disallows removed.
2201pub fn filtered_tool_list(filter: &filter::Filter) -> serde_json::Value {
2202    let all = tool_list();
2203    let filtered: Vec<serde_json::Value> = all
2204        .as_array()
2205        .map(|arr| {
2206            arr.iter()
2207                .filter(|tool| {
2208                    tool.get("name")
2209                        .and_then(|v| v.as_str())
2210                        .map(|n| filter.allows(n))
2211                        .unwrap_or(false)
2212                })
2213                .cloned()
2214                .collect()
2215        })
2216        .unwrap_or_default();
2217    serde_json::Value::Array(filtered)
2218}
2219
2220/// Compact custom field definitions while preserving option IDs for fields
2221/// whose possible values live in `type_config.options`.
2222pub fn compact_custom_fields(fields: &[Value]) -> Value {
2223    let compacted: Vec<Value> = fields
2224        .iter()
2225        .map(|field| {
2226            let mut obj = serde_json::Map::new();
2227            for key in ["id", "name", "type", "required"] {
2228                obj.insert(
2229                    key.to_string(),
2230                    Value::String(flatten_value(field.get(key))),
2231                );
2232            }
2233
2234            if let Some(options) = field
2235                .get("type_config")
2236                .and_then(|config| config.get("options"))
2237                .and_then(|options| options.as_array())
2238            {
2239                obj.insert("options".to_string(), Value::Array(options.clone()));
2240            }
2241
2242            Value::Object(obj)
2243        })
2244        .collect();
2245
2246    Value::Array(compacted)
2247}
2248
2249// ── Tool execution ────────────────────────────────────────────────────────────
2250
2251async fn call_tool(
2252    name: &str,
2253    args: &Value,
2254    client: &ClickUpClient,
2255    workspace_id: &Option<String>,
2256) -> Value {
2257    let result = dispatch_tool(name, args, client, workspace_id).await;
2258    match result {
2259        Ok(v) => tool_result(v.to_string()),
2260        Err(e) => tool_error(format!("Error: {}", e)),
2261    }
2262}
2263
2264async fn dispatch_tool(
2265    name: &str,
2266    args: &Value,
2267    client: &ClickUpClient,
2268    workspace_id: &Option<String>,
2269) -> Result<Value, String> {
2270    let empty = json!({});
2271    let args = if args.is_null() { &empty } else { args };
2272
2273    // Resolve workspace ID from args or config
2274    let resolve_workspace = |args: &Value| -> Result<String, String> {
2275        if let Some(id) = args.get("team_id").and_then(|v| v.as_str()) {
2276            return Ok(id.to_string());
2277        }
2278        workspace_id
2279            .clone()
2280            .ok_or_else(|| "No workspace_id found in config. Please run `clickup setup` or provide team_id in the tool arguments.".to_string())
2281    };
2282
2283    // Normalise a caller-supplied task_id and, if it's a custom-format ID
2284    // (e.g. `PROJ-42`), return the `custom_task_ids=true&team_id=<ws>` query
2285    // fragment that ClickUp requires. Returns the cleaned task id (with any
2286    // `CU-` prefix stripped) plus an optional query fragment to attach to the
2287    // request URL. The returned fragment does NOT include a leading `?` or `&`.
2288    let resolve_task = |args: &Value, key: &str| -> Result<(String, Option<String>), String> {
2289        let raw = args
2290            .get(key)
2291            .and_then(|v| v.as_str())
2292            .ok_or_else(|| format!("Missing required parameter: {}", key))?;
2293        let resolved = git::parse_task_id(raw);
2294        if resolved.is_custom {
2295            let ws = resolve_workspace(args)?;
2296            Ok((
2297                resolved.id,
2298                Some(format!("custom_task_ids=true&team_id={}", ws)),
2299            ))
2300        } else {
2301            Ok((resolved.id, None))
2302        }
2303    };
2304
2305    match name {
2306        "clickup_whoami" => {
2307            let resp = client.get("/v2/user").await.map_err(|e| e.to_string())?;
2308            let user = resp.get("user").cloned().unwrap_or(resp);
2309            Ok(compact_items(&[user], &["id", "username", "email"]))
2310        }
2311
2312        "clickup_workspace_list" => {
2313            let resp = client.get("/v2/team").await.map_err(|e| e.to_string())?;
2314            let teams = resp
2315                .get("teams")
2316                .and_then(|t| t.as_array())
2317                .cloned()
2318                .unwrap_or_default();
2319            let items: Vec<Value> = teams.iter().map(|ws| {
2320                json!({
2321                    "id": ws.get("id"),
2322                    "name": ws.get("name"),
2323                    "members": ws.get("members").and_then(|m| m.as_array()).map(|a| a.len()).unwrap_or(0),
2324                })
2325            }).collect();
2326            Ok(compact_items(&items, &["id", "name", "members"]))
2327        }
2328
2329        "clickup_space_list" => {
2330            let team_id = resolve_workspace(args)?;
2331            let archived = args
2332                .get("archived")
2333                .and_then(|v| v.as_bool())
2334                .unwrap_or(false);
2335            let path = format!("/v2/team/{}/space?archived={}", team_id, archived);
2336            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2337            let spaces = resp
2338                .get("spaces")
2339                .and_then(|s| s.as_array())
2340                .cloned()
2341                .unwrap_or_default();
2342            Ok(compact_items(
2343                &spaces,
2344                &["id", "name", "private", "archived"],
2345            ))
2346        }
2347
2348        "clickup_folder_list" => {
2349            let space_id = args
2350                .get("space_id")
2351                .and_then(|v| v.as_str())
2352                .ok_or("Missing required parameter: space_id")?;
2353            let archived = args
2354                .get("archived")
2355                .and_then(|v| v.as_bool())
2356                .unwrap_or(false);
2357            let path = format!("/v2/space/{}/folder?archived={}", space_id, archived);
2358            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2359            let folders = resp
2360                .get("folders")
2361                .and_then(|f| f.as_array())
2362                .cloned()
2363                .unwrap_or_default();
2364            let items: Vec<Value> = folders
2365                .iter()
2366                .map(|f| {
2367                    let list_count = f
2368                        .get("lists")
2369                        .and_then(|l| l.as_array())
2370                        .map(|a| a.len())
2371                        .unwrap_or(0);
2372                    json!({
2373                        "id": f.get("id"),
2374                        "name": f.get("name"),
2375                        "task_count": f.get("task_count"),
2376                        "list_count": list_count,
2377                    })
2378                })
2379                .collect();
2380            Ok(compact_items(
2381                &items,
2382                &["id", "name", "task_count", "list_count"],
2383            ))
2384        }
2385
2386        "clickup_list_list" => {
2387            let archived = args
2388                .get("archived")
2389                .and_then(|v| v.as_bool())
2390                .unwrap_or(false);
2391            let path = if let Some(folder_id) = args.get("folder_id").and_then(|v| v.as_str()) {
2392                format!("/v2/folder/{}/list?archived={}", folder_id, archived)
2393            } else if let Some(space_id) = args.get("space_id").and_then(|v| v.as_str()) {
2394                format!("/v2/space/{}/list?archived={}", space_id, archived)
2395            } else {
2396                return Err("Provide either folder_id or space_id".to_string());
2397            };
2398            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2399            let lists = resp
2400                .get("lists")
2401                .and_then(|l| l.as_array())
2402                .cloned()
2403                .unwrap_or_default();
2404            Ok(compact_items(
2405                &lists,
2406                &["id", "name", "task_count", "status", "due_date"],
2407            ))
2408        }
2409
2410        "clickup_task_list" => {
2411            let list_id = args
2412                .get("list_id")
2413                .and_then(|v| v.as_str())
2414                .ok_or("Missing required parameter: list_id")?
2415                .to_string();
2416            // Capture filter values once; build_path is called per page.
2417            let include_closed = args.get("include_closed").and_then(|v| v.as_bool());
2418            let statuses: Vec<String> = args
2419                .get("statuses")
2420                .and_then(|v| v.as_array())
2421                .map(|arr| {
2422                    arr.iter()
2423                        .filter_map(|s| s.as_str().map(String::from))
2424                        .collect()
2425                })
2426                .unwrap_or_default();
2427            let assignees: Vec<String> = args
2428                .get("assignees")
2429                .and_then(|v| v.as_array())
2430                .map(|arr| {
2431                    arr.iter()
2432                        .filter_map(|s| s.as_str().map(String::from))
2433                        .collect()
2434                })
2435                .unwrap_or_default();
2436            let pargs = pagination::PageArgs::from_args(args);
2437            pagination::page_dispatch(
2438                &pargs,
2439                client,
2440                "tasks",
2441                &["id", "name", "status", "priority", "assignees", "due_date"],
2442                |page| {
2443                    let mut qs = format!("page={}", page);
2444                    if let Some(ic) = include_closed {
2445                        qs.push_str(&format!("&include_closed={}", ic));
2446                    }
2447                    for s in &statuses {
2448                        qs.push_str(&format!("&statuses[]={}", s));
2449                    }
2450                    for a in &assignees {
2451                        qs.push_str(&format!("&assignees[]={}", a));
2452                    }
2453                    format!("/v2/list/{}/task?{}", list_id, qs)
2454                },
2455            )
2456            .await
2457        }
2458
2459        "clickup_task_get" => {
2460            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2461            let include_subtasks = args
2462                .get("include_subtasks")
2463                .and_then(|v| v.as_bool())
2464                .unwrap_or(false);
2465            let path = match custom_q {
2466                Some(q) => format!(
2467                    "/v2/task/{}?include_subtasks={}&{}",
2468                    task_id, include_subtasks, q
2469                ),
2470                None => format!("/v2/task/{}?include_subtasks={}", task_id, include_subtasks),
2471            };
2472            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2473            Ok(compact_items(
2474                &[resp],
2475                &[
2476                    "id",
2477                    "name",
2478                    "status",
2479                    "priority",
2480                    "assignees",
2481                    "due_date",
2482                    "description",
2483                ],
2484            ))
2485        }
2486
2487        "clickup_task_create" => {
2488            let list_id = args
2489                .get("list_id")
2490                .and_then(|v| v.as_str())
2491                .ok_or("Missing required parameter: list_id")?;
2492            let name = args
2493                .get("name")
2494                .and_then(|v| v.as_str())
2495                .ok_or("Missing required parameter: name")?;
2496            let mut body = json!({"name": name});
2497            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
2498                body["markdown_content"] = json!(desc);
2499            }
2500            if let Some(status) = args.get("status").and_then(|v| v.as_str()) {
2501                body["status"] = json!(status);
2502            }
2503            if let Some(priority) = args.get("priority").and_then(|v| v.as_i64()) {
2504                body["priority"] = json!(priority);
2505            }
2506            if let Some(assignees) = args.get("assignees") {
2507                body["assignees"] = assignees.clone();
2508            }
2509            if let Some(tags) = args.get("tags") {
2510                body["tags"] = tags.clone();
2511            }
2512            if let Some(due_date) = args.get("due_date").and_then(|v| v.as_i64()) {
2513                body["due_date"] = json!(due_date);
2514            }
2515            let path = format!("/v2/list/{}/task", list_id);
2516            let resp = client.post(&path, &body).await.map_err(|e| e.to_string())?;
2517            Ok(compact_items(
2518                &[resp],
2519                &["id", "name", "status", "priority", "assignees", "due_date"],
2520            ))
2521        }
2522
2523        "clickup_task_update" => {
2524            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2525            let mut body = json!({});
2526            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
2527                body["name"] = json!(name);
2528            }
2529            if let Some(status) = args.get("status").and_then(|v| v.as_str()) {
2530                body["status"] = json!(status);
2531            }
2532            if let Some(priority) = args.get("priority").and_then(|v| v.as_i64()) {
2533                body["priority"] = json!(priority);
2534            }
2535            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
2536                body["markdown_content"] = json!(desc);
2537            }
2538            if let Some(te) = args.get("time_estimate").and_then(|v| v.as_i64()) {
2539                body["time_estimate"] = json!(te);
2540            }
2541            if let Some(add) = args.get("add_assignees") {
2542                body["assignees"] = json!({"add": add, "rem": args.get("rem_assignees").cloned().unwrap_or(json!([]))});
2543            } else if let Some(rem) = args.get("rem_assignees") {
2544                body["assignees"] = json!({"add": [], "rem": rem});
2545            }
2546            let path = match custom_q {
2547                Some(q) => format!("/v2/task/{}?{}", task_id, q),
2548                None => format!("/v2/task/{}", task_id),
2549            };
2550            let resp = client.put(&path, &body).await.map_err(|e| e.to_string())?;
2551            Ok(compact_items(
2552                &[resp],
2553                &["id", "name", "status", "priority", "assignees", "due_date"],
2554            ))
2555        }
2556
2557        "clickup_task_delete" => {
2558            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2559            let path = match custom_q {
2560                Some(q) => format!("/v2/task/{}?{}", task_id, q),
2561                None => format!("/v2/task/{}", task_id),
2562            };
2563            client.delete(&path).await.map_err(|e| e.to_string())?;
2564            Ok(json!({"message": format!("Task {} deleted", task_id)}))
2565        }
2566
2567        "clickup_task_search" => {
2568            let team_id = resolve_workspace(args)?;
2569            let base_params = task_search_query_params(args);
2570            let pargs = pagination::PageArgs::from_args(args);
2571            pagination::page_dispatch(
2572                &pargs,
2573                client,
2574                "tasks",
2575                &["id", "name", "status", "priority", "assignees", "due_date"],
2576                |page| {
2577                    let mut parts = vec![format!("page={}", page)];
2578                    parts.extend(base_params.iter().cloned());
2579                    format!("/v2/team/{}/task?{}", team_id, parts.join("&"))
2580                },
2581            )
2582            .await
2583        }
2584
2585        "clickup_comment_list" => {
2586            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2587            let sargs = pagination::StartIdArgs::from_args(args);
2588            pagination::start_id_dispatch(
2589                &sargs,
2590                client,
2591                "comments",
2592                &["id", "user", "date", "comment_text"],
2593                |start, start_id| {
2594                    let mut qs = String::new();
2595                    if let Some(q) = &custom_q {
2596                        qs.push_str(q);
2597                    }
2598                    if let (Some(s), Some(sid)) = (start, start_id) {
2599                        if !qs.is_empty() {
2600                            qs.push('&');
2601                        }
2602                        qs.push_str(&format!("start={}&start_id={}", s, sid));
2603                    }
2604                    if qs.is_empty() {
2605                        format!("/v2/task/{}/comment", task_id)
2606                    } else {
2607                        format!("/v2/task/{}/comment?{}", task_id, qs)
2608                    }
2609                },
2610            )
2611            .await
2612        }
2613
2614        "clickup_comment_create" => {
2615            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2616            let text = args
2617                .get("text")
2618                .and_then(|v| v.as_str())
2619                .ok_or("Missing required parameter: text")?;
2620            let mut body = json!({"comment_text": text});
2621            if let Some(assignee) = args.get("assignee").and_then(|v| v.as_i64()) {
2622                body["assignee"] = json!(assignee);
2623            }
2624            if let Some(notify_all) = args.get("notify_all").and_then(|v| v.as_bool()) {
2625                body["notify_all"] = json!(notify_all);
2626            }
2627            let path = match custom_q {
2628                Some(q) => format!("/v2/task/{}/comment?{}", task_id, q),
2629                None => format!("/v2/task/{}/comment", task_id),
2630            };
2631            let resp = client.post(&path, &body).await.map_err(|e| e.to_string())?;
2632            Ok(json!({"message": "Comment created", "id": resp.get("id")}))
2633        }
2634
2635        "clickup_field_list" => {
2636            let list_id = args
2637                .get("list_id")
2638                .and_then(|v| v.as_str())
2639                .ok_or("Missing required parameter: list_id")?;
2640            let path = format!("/v2/list/{}/field", list_id);
2641            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2642            let fields = resp
2643                .get("fields")
2644                .and_then(|f| f.as_array())
2645                .cloned()
2646                .unwrap_or_default();
2647            Ok(compact_custom_fields(&fields))
2648        }
2649
2650        "clickup_field_set" => {
2651            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2652            let field_id = args
2653                .get("field_id")
2654                .and_then(|v| v.as_str())
2655                .ok_or("Missing required parameter: field_id")?;
2656            let value = args
2657                .get("value")
2658                .ok_or("Missing required parameter: value")?;
2659            let body = json!({"value": value});
2660            let path = match custom_q {
2661                Some(q) => format!("/v2/task/{}/field/{}?{}", task_id, field_id, q),
2662                None => format!("/v2/task/{}/field/{}", task_id, field_id),
2663            };
2664            client.post(&path, &body).await.map_err(|e| e.to_string())?;
2665            Ok(json!({"message": format!("Field {} set on task {}", field_id, task_id)}))
2666        }
2667
2668        "clickup_time_start" => {
2669            let team_id = resolve_workspace(args)?;
2670            let mut body = json!({});
2671            if let Some(task_id) = args.get("task_id").and_then(|v| v.as_str()) {
2672                body["tid"] = json!(task_id);
2673            }
2674            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
2675                body["description"] = json!(desc);
2676            }
2677            if let Some(billable) = args.get("billable").and_then(|v| v.as_bool()) {
2678                body["billable"] = json!(billable);
2679            }
2680            let path = format!("/v2/team/{}/time_entries/start", team_id);
2681            let resp = client.post(&path, &body).await.map_err(|e| e.to_string())?;
2682            let data = resp.get("data").cloned().unwrap_or(resp);
2683            Ok(compact_items(
2684                &[data],
2685                &["id", "task", "duration", "start", "billable"],
2686            ))
2687        }
2688
2689        "clickup_time_stop" => {
2690            let team_id = resolve_workspace(args)?;
2691            let path = format!("/v2/team/{}/time_entries/stop", team_id);
2692            let resp = client
2693                .post(&path, &json!({}))
2694                .await
2695                .map_err(|e| e.to_string())?;
2696            let data = resp.get("data").cloned().unwrap_or(resp);
2697            Ok(compact_items(
2698                &[data],
2699                &["id", "task", "duration", "start", "end", "billable"],
2700            ))
2701        }
2702
2703        "clickup_time_list" => {
2704            let team_id = resolve_workspace(args)?;
2705            let mut qs = String::new();
2706            if let Some(start_date) = args.get("start_date").and_then(|v| v.as_i64()) {
2707                qs.push_str(&format!("&start_date={}", start_date));
2708            }
2709            if let Some(end_date) = args.get("end_date").and_then(|v| v.as_i64()) {
2710                qs.push_str(&format!("&end_date={}", end_date));
2711            }
2712            if let Some(task_id) = args.get("task_id").and_then(|v| v.as_str()) {
2713                qs.push_str(&format!("&task_id={}", task_id));
2714            }
2715            let path = format!(
2716                "/v2/team/{}/time_entries?{}",
2717                team_id,
2718                qs.trim_start_matches('&')
2719            );
2720            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2721            let entries = resp
2722                .get("data")
2723                .and_then(|d| d.as_array())
2724                .cloned()
2725                .unwrap_or_default();
2726            Ok(compact_items(
2727                &entries,
2728                &["id", "task", "duration", "start", "billable"],
2729            ))
2730        }
2731
2732        "clickup_checklist_create" => {
2733            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2734            let name = args
2735                .get("name")
2736                .and_then(|v| v.as_str())
2737                .ok_or("Missing required parameter: name")?;
2738            let path = match custom_q {
2739                Some(q) => format!("/v2/task/{}/checklist?{}", task_id, q),
2740                None => format!("/v2/task/{}/checklist", task_id),
2741            };
2742            let body = json!({"name": name});
2743            let resp = client.post(&path, &body).await.map_err(|e| e.to_string())?;
2744            let checklist = resp.get("checklist").cloned().unwrap_or(resp);
2745            Ok(compact_items(&[checklist], &["id", "name"]))
2746        }
2747
2748        "clickup_checklist_delete" => {
2749            let checklist_id = args
2750                .get("checklist_id")
2751                .and_then(|v| v.as_str())
2752                .ok_or("Missing required parameter: checklist_id")?;
2753            let path = format!("/v2/checklist/{}", checklist_id);
2754            client.delete(&path).await.map_err(|e| e.to_string())?;
2755            Ok(json!({"message": format!("Checklist {} deleted", checklist_id)}))
2756        }
2757
2758        "clickup_goal_list" => {
2759            let team_id = resolve_workspace(args)?;
2760            let path = format!("/v2/team/{}/goal", team_id);
2761            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2762            let goals = resp
2763                .get("goals")
2764                .and_then(|g| g.as_array())
2765                .cloned()
2766                .unwrap_or_default();
2767            Ok(compact_items(
2768                &goals,
2769                &["id", "name", "percent_completed", "due_date"],
2770            ))
2771        }
2772
2773        "clickup_goal_get" => {
2774            let goal_id = args
2775                .get("goal_id")
2776                .and_then(|v| v.as_str())
2777                .ok_or("Missing required parameter: goal_id")?;
2778            let path = format!("/v2/goal/{}", goal_id);
2779            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2780            let goal = resp.get("goal").cloned().unwrap_or(resp);
2781            Ok(compact_items(
2782                &[goal],
2783                &["id", "name", "percent_completed", "due_date", "description"],
2784            ))
2785        }
2786
2787        "clickup_goal_create" => {
2788            let team_id = resolve_workspace(args)?;
2789            let name = args
2790                .get("name")
2791                .and_then(|v| v.as_str())
2792                .ok_or("Missing required parameter: name")?;
2793            let mut body = json!({"name": name});
2794            if let Some(due_date) = args.get("due_date").and_then(|v| v.as_i64()) {
2795                body["due_date"] = json!(due_date);
2796            }
2797            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
2798                body["description"] = json!(desc);
2799            }
2800            // ClickUp's create-goal spec requires `multiple_owners` (bool).
2801            // Derive it from the size of the owner_ids array.
2802            let owner_count = args
2803                .get("owner_ids")
2804                .and_then(|v| v.as_array())
2805                .map(|a| a.len())
2806                .unwrap_or(0);
2807            body["multiple_owners"] = json!(owner_count > 1);
2808            if let Some(owner_ids) = args.get("owner_ids") {
2809                body["owners"] = owner_ids.clone();
2810            }
2811            let path = format!("/v2/team/{}/goal", team_id);
2812            let resp = client.post(&path, &body).await.map_err(|e| e.to_string())?;
2813            let goal = resp.get("goal").cloned().unwrap_or(resp);
2814            Ok(compact_items(&[goal], &["id", "name"]))
2815        }
2816
2817        "clickup_goal_update" => {
2818            let goal_id = args
2819                .get("goal_id")
2820                .and_then(|v| v.as_str())
2821                .ok_or("Missing required parameter: goal_id")?;
2822            let mut body = json!({});
2823            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
2824                body["name"] = json!(name);
2825            }
2826            if let Some(due_date) = args.get("due_date").and_then(|v| v.as_i64()) {
2827                body["due_date"] = json!(due_date);
2828            }
2829            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
2830                body["description"] = json!(desc);
2831            }
2832            let path = format!("/v2/goal/{}", goal_id);
2833            let resp = client.put(&path, &body).await.map_err(|e| e.to_string())?;
2834            let goal = resp.get("goal").cloned().unwrap_or(resp);
2835            Ok(compact_items(&[goal], &["id", "name"]))
2836        }
2837
2838        "clickup_view_list" => {
2839            let path = if let Some(space_id) = args.get("space_id").and_then(|v| v.as_str()) {
2840                format!("/v2/space/{}/view", space_id)
2841            } else if let Some(folder_id) = args.get("folder_id").and_then(|v| v.as_str()) {
2842                format!("/v2/folder/{}/view", folder_id)
2843            } else if let Some(list_id) = args.get("list_id").and_then(|v| v.as_str()) {
2844                format!("/v2/list/{}/view", list_id)
2845            } else {
2846                let team_id = resolve_workspace(args)?;
2847                format!("/v2/team/{}/view", team_id)
2848            };
2849            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2850            let views = resp
2851                .get("views")
2852                .and_then(|v| v.as_array())
2853                .cloned()
2854                .unwrap_or_default();
2855            Ok(compact_items(&views, &["id", "name", "type"]))
2856        }
2857
2858        "clickup_view_tasks" => {
2859            let view_id = args
2860                .get("view_id")
2861                .and_then(|v| v.as_str())
2862                .ok_or("Missing required parameter: view_id")?
2863                .to_string();
2864            let pargs = pagination::PageArgs::from_args(args);
2865            pagination::page_dispatch(
2866                &pargs,
2867                client,
2868                "tasks",
2869                &["id", "name", "status", "priority", "assignees", "due_date"],
2870                |page| format!("/v2/view/{}/task?page={}", view_id, page),
2871            )
2872            .await
2873        }
2874
2875        "clickup_doc_list" => {
2876            let team_id = resolve_workspace(args)?;
2877            let cargs = pagination::CursorArgs::from_args(args);
2878            pagination::cursor_dispatch(
2879                &cargs,
2880                client,
2881                &["data", "docs"],
2882                &["id", "name", "date_created"],
2883                |cursor| match cursor {
2884                    Some(c) => format!("/v3/workspaces/{}/docs?cursor={}", team_id, c),
2885                    None => format!("/v3/workspaces/{}/docs", team_id),
2886                },
2887            )
2888            .await
2889        }
2890
2891        "clickup_doc_get" => {
2892            let team_id = resolve_workspace(args)?;
2893            let doc_id = args
2894                .get("doc_id")
2895                .and_then(|v| v.as_str())
2896                .ok_or("Missing required parameter: doc_id")?;
2897            let path = format!("/v3/workspaces/{}/docs/{}", team_id, doc_id);
2898            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2899            Ok(compact_items(&[resp], &["id", "name", "date_created"]))
2900        }
2901
2902        "clickup_doc_pages" => {
2903            let team_id = resolve_workspace(args)?;
2904            let doc_id = args
2905                .get("doc_id")
2906                .and_then(|v| v.as_str())
2907                .ok_or("Missing required parameter: doc_id")?;
2908            let content = args
2909                .get("content")
2910                .and_then(|v| v.as_bool())
2911                .unwrap_or(false);
2912            let path = format!("/v3/workspaces/{}/docs/{}/pages?content_format=text/md&max_page_depth=-1&include_content={}", team_id, doc_id, content);
2913            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2914            let pages = resp
2915                .get("pages")
2916                .and_then(|p| p.as_array())
2917                .cloned()
2918                .unwrap_or_default();
2919            Ok(compact_items(&pages, &["id", "name"]))
2920        }
2921
2922        "clickup_tag_list" => {
2923            let space_id = args
2924                .get("space_id")
2925                .and_then(|v| v.as_str())
2926                .ok_or("Missing required parameter: space_id")?;
2927            let path = format!("/v2/space/{}/tag", space_id);
2928            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2929            let tags = resp
2930                .get("tags")
2931                .and_then(|t| t.as_array())
2932                .cloned()
2933                .unwrap_or_default();
2934            Ok(compact_items(&tags, &["name", "tag_fg", "tag_bg"]))
2935        }
2936
2937        "clickup_task_add_tag" => {
2938            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2939            let tag_name = args
2940                .get("tag_name")
2941                .and_then(|v| v.as_str())
2942                .ok_or("Missing required parameter: tag_name")?;
2943            let path = match custom_q {
2944                Some(q) => format!("/v2/task/{}/tag/{}?{}", task_id, tag_name, q),
2945                None => format!("/v2/task/{}/tag/{}", task_id, tag_name),
2946            };
2947            client
2948                .post(&path, &json!({}))
2949                .await
2950                .map_err(|e| e.to_string())?;
2951            Ok(json!({"message": format!("Tag '{}' added to task {}", tag_name, task_id)}))
2952        }
2953
2954        "clickup_task_remove_tag" => {
2955            let (task_id, custom_q) = resolve_task(args, "task_id")?;
2956            let tag_name = args
2957                .get("tag_name")
2958                .and_then(|v| v.as_str())
2959                .ok_or("Missing required parameter: tag_name")?;
2960            let path = match custom_q {
2961                Some(q) => format!("/v2/task/{}/tag/{}?{}", task_id, tag_name, q),
2962                None => format!("/v2/task/{}/tag/{}", task_id, tag_name),
2963            };
2964            client.delete(&path).await.map_err(|e| e.to_string())?;
2965            Ok(json!({"message": format!("Tag '{}' removed from task {}", tag_name, task_id)}))
2966        }
2967
2968        "clickup_webhook_list" => {
2969            let team_id = resolve_workspace(args)?;
2970            let path = format!("/v2/team/{}/webhook", team_id);
2971            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2972            let webhooks = resp
2973                .get("webhooks")
2974                .and_then(|w| w.as_array())
2975                .cloned()
2976                .unwrap_or_default();
2977            Ok(compact_items(
2978                &webhooks,
2979                &["id", "endpoint", "events", "status"],
2980            ))
2981        }
2982
2983        "clickup_member_list" => {
2984            let path = if let Some(task_id) = args.get("task_id").and_then(|v| v.as_str()) {
2985                format!("/v2/task/{}/member", task_id)
2986            } else if let Some(list_id) = args.get("list_id").and_then(|v| v.as_str()) {
2987                format!("/v2/list/{}/member", list_id)
2988            } else {
2989                return Err("Provide either task_id or list_id".to_string());
2990            };
2991            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
2992            let members = resp
2993                .get("members")
2994                .and_then(|m| m.as_array())
2995                .cloned()
2996                .unwrap_or_default();
2997            Ok(compact_items(&members, &["id", "username", "email"]))
2998        }
2999
3000        "clickup_template_list" => {
3001            let team_id = resolve_workspace(args)?;
3002            let pargs = pagination::PageArgs::from_args(args);
3003            pagination::page_dispatch(&pargs, client, "templates", &["id", "name"], |page| {
3004                format!("/v2/team/{}/taskTemplate?page={}", team_id, page)
3005            })
3006            .await
3007        }
3008
3009        "clickup_space_get" => {
3010            let space_id = args
3011                .get("space_id")
3012                .and_then(|v| v.as_str())
3013                .ok_or("Missing required parameter: space_id")?;
3014            let resp = client
3015                .get(&format!("/v2/space/{}", space_id))
3016                .await
3017                .map_err(|e| e.to_string())?;
3018            Ok(compact_items(
3019                &[resp],
3020                &["id", "name", "private", "archived"],
3021            ))
3022        }
3023
3024        "clickup_space_create" => {
3025            let team_id = resolve_workspace(args)?;
3026            let name = args
3027                .get("name")
3028                .and_then(|v| v.as_str())
3029                .ok_or("Missing required parameter: name")?;
3030            let mut body = json!({"name": name});
3031            if let Some(private) = args.get("private").and_then(|v| v.as_bool()) {
3032                body["private"] = json!(private);
3033            }
3034            let resp = client
3035                .post(&format!("/v2/team/{}/space", team_id), &body)
3036                .await
3037                .map_err(|e| e.to_string())?;
3038            Ok(compact_items(&[resp], &["id", "name", "private"]))
3039        }
3040
3041        "clickup_space_update" => {
3042            let space_id = args
3043                .get("space_id")
3044                .and_then(|v| v.as_str())
3045                .ok_or("Missing required parameter: space_id")?;
3046            let mut body = json!({});
3047            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
3048                body["name"] = json!(name);
3049            }
3050            if let Some(private) = args.get("private").and_then(|v| v.as_bool()) {
3051                body["private"] = json!(private);
3052            }
3053            if let Some(archived) = args.get("archived").and_then(|v| v.as_bool()) {
3054                body["archived"] = json!(archived);
3055            }
3056            let resp = client
3057                .put(&format!("/v2/space/{}", space_id), &body)
3058                .await
3059                .map_err(|e| e.to_string())?;
3060            Ok(compact_items(
3061                &[resp],
3062                &["id", "name", "private", "archived"],
3063            ))
3064        }
3065
3066        "clickup_space_delete" => {
3067            let space_id = args
3068                .get("space_id")
3069                .and_then(|v| v.as_str())
3070                .ok_or("Missing required parameter: space_id")?;
3071            client
3072                .delete(&format!("/v2/space/{}", space_id))
3073                .await
3074                .map_err(|e| e.to_string())?;
3075            Ok(json!({"message": format!("Space {} deleted", space_id)}))
3076        }
3077
3078        "clickup_folder_get" => {
3079            let folder_id = args
3080                .get("folder_id")
3081                .and_then(|v| v.as_str())
3082                .ok_or("Missing required parameter: folder_id")?;
3083            let resp = client
3084                .get(&format!("/v2/folder/{}", folder_id))
3085                .await
3086                .map_err(|e| e.to_string())?;
3087            Ok(compact_items(&[resp], &["id", "name", "task_count"]))
3088        }
3089
3090        "clickup_folder_create" => {
3091            let space_id = args
3092                .get("space_id")
3093                .and_then(|v| v.as_str())
3094                .ok_or("Missing required parameter: space_id")?;
3095            let name = args
3096                .get("name")
3097                .and_then(|v| v.as_str())
3098                .ok_or("Missing required parameter: name")?;
3099            let body = json!({"name": name});
3100            let resp = client
3101                .post(&format!("/v2/space/{}/folder", space_id), &body)
3102                .await
3103                .map_err(|e| e.to_string())?;
3104            Ok(compact_items(&[resp], &["id", "name"]))
3105        }
3106
3107        "clickup_folder_update" => {
3108            let folder_id = args
3109                .get("folder_id")
3110                .and_then(|v| v.as_str())
3111                .ok_or("Missing required parameter: folder_id")?;
3112            let name = args
3113                .get("name")
3114                .and_then(|v| v.as_str())
3115                .ok_or("Missing required parameter: name")?;
3116            let body = json!({"name": name});
3117            let resp = client
3118                .put(&format!("/v2/folder/{}", folder_id), &body)
3119                .await
3120                .map_err(|e| e.to_string())?;
3121            Ok(compact_items(&[resp], &["id", "name"]))
3122        }
3123
3124        "clickup_folder_delete" => {
3125            let folder_id = args
3126                .get("folder_id")
3127                .and_then(|v| v.as_str())
3128                .ok_or("Missing required parameter: folder_id")?;
3129            client
3130                .delete(&format!("/v2/folder/{}", folder_id))
3131                .await
3132                .map_err(|e| e.to_string())?;
3133            Ok(json!({"message": format!("Folder {} deleted", folder_id)}))
3134        }
3135
3136        "clickup_list_get" => {
3137            let list_id = args
3138                .get("list_id")
3139                .and_then(|v| v.as_str())
3140                .ok_or("Missing required parameter: list_id")?;
3141            let resp = client
3142                .get(&format!("/v2/list/{}", list_id))
3143                .await
3144                .map_err(|e| e.to_string())?;
3145            Ok(compact_items(
3146                &[resp],
3147                &["id", "name", "task_count", "status", "due_date"],
3148            ))
3149        }
3150
3151        "clickup_list_create" => {
3152            let name = args
3153                .get("name")
3154                .and_then(|v| v.as_str())
3155                .ok_or("Missing required parameter: name")?;
3156            let mut body = json!({"name": name});
3157            if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
3158                body["markdown_content"] = json!(content);
3159            }
3160            if let Some(due_date) = args.get("due_date").and_then(|v| v.as_i64()) {
3161                body["due_date"] = json!(due_date);
3162            }
3163            if let Some(status) = args.get("status").and_then(|v| v.as_str()) {
3164                body["status"] = json!(status);
3165            }
3166            let path = if let Some(folder_id) = args.get("folder_id").and_then(|v| v.as_str()) {
3167                format!("/v2/folder/{}/list", folder_id)
3168            } else if let Some(space_id) = args.get("space_id").and_then(|v| v.as_str()) {
3169                format!("/v2/space/{}/list", space_id)
3170            } else {
3171                return Err("Provide either folder_id or space_id".to_string());
3172            };
3173            let resp = client.post(&path, &body).await.map_err(|e| e.to_string())?;
3174            Ok(compact_items(&[resp], &["id", "name"]))
3175        }
3176
3177        "clickup_list_update" => {
3178            let list_id = args
3179                .get("list_id")
3180                .and_then(|v| v.as_str())
3181                .ok_or("Missing required parameter: list_id")?;
3182            let mut body = json!({});
3183            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
3184                body["name"] = json!(name);
3185            }
3186            if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
3187                body["markdown_content"] = json!(content);
3188            }
3189            if let Some(due_date) = args.get("due_date").and_then(|v| v.as_i64()) {
3190                body["due_date"] = json!(due_date);
3191            }
3192            if let Some(status) = args.get("status").and_then(|v| v.as_str()) {
3193                body["status"] = json!(status);
3194            }
3195            let resp = client
3196                .put(&format!("/v2/list/{}", list_id), &body)
3197                .await
3198                .map_err(|e| e.to_string())?;
3199            Ok(compact_items(
3200                &[resp],
3201                &["id", "name", "task_count", "status"],
3202            ))
3203        }
3204
3205        "clickup_list_delete" => {
3206            let list_id = args
3207                .get("list_id")
3208                .and_then(|v| v.as_str())
3209                .ok_or("Missing required parameter: list_id")?;
3210            client
3211                .delete(&format!("/v2/list/{}", list_id))
3212                .await
3213                .map_err(|e| e.to_string())?;
3214            Ok(json!({"message": format!("List {} deleted", list_id)}))
3215        }
3216
3217        "clickup_list_add_task" => {
3218            let list_id = args
3219                .get("list_id")
3220                .and_then(|v| v.as_str())
3221                .ok_or("Missing required parameter: list_id")?;
3222            let task_id = args
3223                .get("task_id")
3224                .and_then(|v| v.as_str())
3225                .ok_or("Missing required parameter: task_id")?;
3226            client
3227                .post(
3228                    &format!("/v2/list/{}/task/{}", list_id, task_id),
3229                    &json!({}),
3230                )
3231                .await
3232                .map_err(|e| e.to_string())?;
3233            Ok(json!({"message": format!("Task {} added to list {}", task_id, list_id)}))
3234        }
3235
3236        "clickup_list_remove_task" => {
3237            let list_id = args
3238                .get("list_id")
3239                .and_then(|v| v.as_str())
3240                .ok_or("Missing required parameter: list_id")?;
3241            let task_id = args
3242                .get("task_id")
3243                .and_then(|v| v.as_str())
3244                .ok_or("Missing required parameter: task_id")?;
3245            client
3246                .delete(&format!("/v2/list/{}/task/{}", list_id, task_id))
3247                .await
3248                .map_err(|e| e.to_string())?;
3249            Ok(json!({"message": format!("Task {} removed from list {}", task_id, list_id)}))
3250        }
3251
3252        "clickup_comment_update" => {
3253            let comment_id = args
3254                .get("comment_id")
3255                .and_then(|v| v.as_str())
3256                .ok_or("Missing required parameter: comment_id")?;
3257            let text = args
3258                .get("text")
3259                .and_then(|v| v.as_str())
3260                .ok_or("Missing required parameter: text")?;
3261            let mut body = json!({"comment_text": text});
3262            if let Some(assignee) = args.get("assignee").and_then(|v| v.as_i64()) {
3263                body["assignee"] = json!(assignee);
3264            }
3265            if let Some(resolved) = args.get("resolved").and_then(|v| v.as_bool()) {
3266                body["resolved"] = json!(resolved);
3267            }
3268            client
3269                .put(&format!("/v2/comment/{}", comment_id), &body)
3270                .await
3271                .map_err(|e| e.to_string())?;
3272            Ok(json!({"message": format!("Comment {} updated", comment_id)}))
3273        }
3274
3275        "clickup_comment_delete" => {
3276            let comment_id = args
3277                .get("comment_id")
3278                .and_then(|v| v.as_str())
3279                .ok_or("Missing required parameter: comment_id")?;
3280            client
3281                .delete(&format!("/v2/comment/{}", comment_id))
3282                .await
3283                .map_err(|e| e.to_string())?;
3284            Ok(json!({"message": format!("Comment {} deleted", comment_id)}))
3285        }
3286
3287        "clickup_task_add_dep" => {
3288            let (task_id, custom_q) = resolve_task(args, "task_id")?;
3289            let mut body = json!({});
3290            if let Some(dep) = args.get("depends_on").and_then(|v| v.as_str()) {
3291                body["depends_on"] = json!(dep);
3292            }
3293            if let Some(dep) = args.get("dependency_of").and_then(|v| v.as_str()) {
3294                body["dependency_of"] = json!(dep);
3295            }
3296            let path = match custom_q {
3297                Some(q) => format!("/v2/task/{}/dependency?{}", task_id, q),
3298                None => format!("/v2/task/{}/dependency", task_id),
3299            };
3300            client.post(&path, &body).await.map_err(|e| e.to_string())?;
3301            Ok(json!({"message": format!("Dependency added to task {}", task_id)}))
3302        }
3303
3304        "clickup_task_remove_dep" => {
3305            let (task_id, custom_q) = resolve_task(args, "task_id")?;
3306            let mut body = json!({});
3307            if let Some(dep) = args.get("depends_on").and_then(|v| v.as_str()) {
3308                body["depends_on"] = json!(dep);
3309            }
3310            if let Some(dep) = args.get("dependency_of").and_then(|v| v.as_str()) {
3311                body["dependency_of"] = json!(dep);
3312            }
3313            let path = match custom_q {
3314                Some(q) => format!("/v2/task/{}/dependency?{}", task_id, q),
3315                None => format!("/v2/task/{}/dependency", task_id),
3316            };
3317            client
3318                .delete_with_body(&path, &body)
3319                .await
3320                .map_err(|e| e.to_string())?;
3321            Ok(json!({"message": format!("Dependency removed from task {}", task_id)}))
3322        }
3323
3324        "clickup_task_link" => {
3325            let (task_id, custom_q) = resolve_task(args, "task_id")?;
3326            let links_to = args
3327                .get("links_to")
3328                .and_then(|v| v.as_str())
3329                .ok_or("Missing required parameter: links_to")?;
3330            let path = match custom_q {
3331                Some(q) => format!("/v2/task/{}/link/{}?{}", task_id, links_to, q),
3332                None => format!("/v2/task/{}/link/{}", task_id, links_to),
3333            };
3334            let resp = client
3335                .post(&path, &json!({}))
3336                .await
3337                .map_err(|e| e.to_string())?;
3338            Ok(json!({"message": format!("Task {} linked to {}", task_id, links_to), "data": resp}))
3339        }
3340
3341        "clickup_task_unlink" => {
3342            let (task_id, custom_q) = resolve_task(args, "task_id")?;
3343            let links_to = args
3344                .get("links_to")
3345                .and_then(|v| v.as_str())
3346                .ok_or("Missing required parameter: links_to")?;
3347            let path = match custom_q {
3348                Some(q) => format!("/v2/task/{}/link/{}?{}", task_id, links_to, q),
3349                None => format!("/v2/task/{}/link/{}", task_id, links_to),
3350            };
3351            client.delete(&path).await.map_err(|e| e.to_string())?;
3352            Ok(json!({"message": format!("Task {} unlinked from {}", task_id, links_to)}))
3353        }
3354
3355        "clickup_goal_delete" => {
3356            let goal_id = args
3357                .get("goal_id")
3358                .and_then(|v| v.as_str())
3359                .ok_or("Missing required parameter: goal_id")?;
3360            client
3361                .delete(&format!("/v2/goal/{}", goal_id))
3362                .await
3363                .map_err(|e| e.to_string())?;
3364            Ok(json!({"message": format!("Goal {} deleted", goal_id)}))
3365        }
3366
3367        "clickup_goal_add_kr" => {
3368            let goal_id = args
3369                .get("goal_id")
3370                .and_then(|v| v.as_str())
3371                .ok_or("Missing required parameter: goal_id")?;
3372            let name = args
3373                .get("name")
3374                .and_then(|v| v.as_str())
3375                .ok_or("Missing required parameter: name")?;
3376            let kr_type = args
3377                .get("type")
3378                .and_then(|v| v.as_str())
3379                .ok_or("Missing required parameter: type")?;
3380            let steps_start = args
3381                .get("steps_start")
3382                .and_then(|v| v.as_f64())
3383                .ok_or("Missing required parameter: steps_start")?;
3384            let steps_end = args
3385                .get("steps_end")
3386                .and_then(|v| v.as_f64())
3387                .ok_or("Missing required parameter: steps_end")?;
3388            let mut body = json!({"name": name, "type": kr_type, "steps_start": steps_start, "steps_end": steps_end});
3389            if let Some(unit) = args.get("unit").and_then(|v| v.as_str()) {
3390                body["unit"] = json!(unit);
3391            }
3392            if let Some(owners) = args.get("owner_ids") {
3393                body["owners"] = owners.clone();
3394            }
3395            if let Some(task_ids) = args.get("task_ids") {
3396                body["task_ids"] = task_ids.clone();
3397            }
3398            if let Some(list_ids) = args.get("list_ids") {
3399                body["list_ids"] = list_ids.clone();
3400            }
3401            let resp = client
3402                .post(&format!("/v2/goal/{}/key_result", goal_id), &body)
3403                .await
3404                .map_err(|e| e.to_string())?;
3405            let kr = resp.get("key_result").cloned().unwrap_or(resp);
3406            Ok(compact_items(
3407                &[kr],
3408                &[
3409                    "id",
3410                    "name",
3411                    "type",
3412                    "steps_start",
3413                    "steps_end",
3414                    "steps_current",
3415                ],
3416            ))
3417        }
3418
3419        "clickup_goal_update_kr" => {
3420            let kr_id = args
3421                .get("kr_id")
3422                .and_then(|v| v.as_str())
3423                .ok_or("Missing required parameter: kr_id")?;
3424            let mut body = json!({});
3425            if let Some(v) = args.get("steps_current").and_then(|v| v.as_f64()) {
3426                body["steps_current"] = json!(v);
3427            }
3428            if let Some(v) = args.get("name").and_then(|v| v.as_str()) {
3429                body["name"] = json!(v);
3430            }
3431            if let Some(v) = args.get("unit").and_then(|v| v.as_str()) {
3432                body["unit"] = json!(v);
3433            }
3434            let resp = client
3435                .put(&format!("/v2/key_result/{}", kr_id), &body)
3436                .await
3437                .map_err(|e| e.to_string())?;
3438            let kr = resp.get("key_result").cloned().unwrap_or(resp);
3439            Ok(compact_items(
3440                &[kr],
3441                &["id", "name", "steps_current", "steps_end"],
3442            ))
3443        }
3444
3445        "clickup_goal_delete_kr" => {
3446            let kr_id = args
3447                .get("kr_id")
3448                .and_then(|v| v.as_str())
3449                .ok_or("Missing required parameter: kr_id")?;
3450            client
3451                .delete(&format!("/v2/key_result/{}", kr_id))
3452                .await
3453                .map_err(|e| e.to_string())?;
3454            Ok(json!({"message": format!("Key result {} deleted", kr_id)}))
3455        }
3456
3457        "clickup_time_get" => {
3458            let team_id = resolve_workspace(args)?;
3459            let timer_id = args
3460                .get("timer_id")
3461                .and_then(|v| v.as_str())
3462                .ok_or("Missing required parameter: timer_id")?;
3463            let resp = client
3464                .get(&format!("/v2/team/{}/time_entries/{}", team_id, timer_id))
3465                .await
3466                .map_err(|e| e.to_string())?;
3467            let data = resp.get("data").cloned().unwrap_or(resp);
3468            Ok(compact_items(
3469                &[data],
3470                &["id", "task", "duration", "start", "end", "billable"],
3471            ))
3472        }
3473
3474        "clickup_time_create" => {
3475            let team_id = resolve_workspace(args)?;
3476            let start = args
3477                .get("start")
3478                .and_then(|v| v.as_i64())
3479                .ok_or("Missing required parameter: start")?;
3480            let duration = args
3481                .get("duration")
3482                .and_then(|v| v.as_i64())
3483                .ok_or("Missing required parameter: duration")?;
3484            let mut body = json!({"start": start, "duration": duration});
3485            if let Some(task_id) = args.get("task_id").and_then(|v| v.as_str()) {
3486                body["tid"] = json!(task_id);
3487            }
3488            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
3489                body["description"] = json!(desc);
3490            }
3491            if let Some(billable) = args.get("billable").and_then(|v| v.as_bool()) {
3492                body["billable"] = json!(billable);
3493            }
3494            let resp = client
3495                .post(&format!("/v2/team/{}/time_entries", team_id), &body)
3496                .await
3497                .map_err(|e| e.to_string())?;
3498            let data = resp.get("data").cloned().unwrap_or(resp);
3499            Ok(compact_items(
3500                &[data],
3501                &["id", "task", "duration", "start", "billable"],
3502            ))
3503        }
3504
3505        "clickup_time_update" => {
3506            let team_id = resolve_workspace(args)?;
3507            let timer_id = args
3508                .get("timer_id")
3509                .and_then(|v| v.as_str())
3510                .ok_or("Missing required parameter: timer_id")?;
3511            let mut body = json!({});
3512            if let Some(start) = args.get("start").and_then(|v| v.as_i64()) {
3513                body["start"] = json!(start);
3514            }
3515            if let Some(duration) = args.get("duration").and_then(|v| v.as_i64()) {
3516                body["duration"] = json!(duration);
3517            }
3518            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
3519                body["description"] = json!(desc);
3520            }
3521            if let Some(billable) = args.get("billable").and_then(|v| v.as_bool()) {
3522                body["billable"] = json!(billable);
3523            }
3524            let resp = client
3525                .put(
3526                    &format!("/v2/team/{}/time_entries/{}", team_id, timer_id),
3527                    &body,
3528                )
3529                .await
3530                .map_err(|e| e.to_string())?;
3531            let data = resp.get("data").cloned().unwrap_or(resp);
3532            Ok(compact_items(
3533                &[data],
3534                &["id", "task", "duration", "start", "billable"],
3535            ))
3536        }
3537
3538        "clickup_time_delete" => {
3539            let team_id = resolve_workspace(args)?;
3540            let timer_id = args
3541                .get("timer_id")
3542                .and_then(|v| v.as_str())
3543                .ok_or("Missing required parameter: timer_id")?;
3544            client
3545                .delete(&format!("/v2/team/{}/time_entries/{}", team_id, timer_id))
3546                .await
3547                .map_err(|e| e.to_string())?;
3548            Ok(json!({"message": format!("Time entry {} deleted", timer_id)}))
3549        }
3550
3551        "clickup_view_get" => {
3552            let view_id = args
3553                .get("view_id")
3554                .and_then(|v| v.as_str())
3555                .ok_or("Missing required parameter: view_id")?;
3556            let resp = client
3557                .get(&format!("/v2/view/{}", view_id))
3558                .await
3559                .map_err(|e| e.to_string())?;
3560            let view = resp.get("view").cloned().unwrap_or(resp);
3561            Ok(compact_items(&[view], &["id", "name", "type"]))
3562        }
3563
3564        "clickup_view_create" => {
3565            let scope = args
3566                .get("scope")
3567                .and_then(|v| v.as_str())
3568                .ok_or("Missing required parameter: scope")?;
3569            let scope_id = args
3570                .get("scope_id")
3571                .and_then(|v| v.as_str())
3572                .ok_or("Missing required parameter: scope_id")?;
3573            let name = args
3574                .get("name")
3575                .and_then(|v| v.as_str())
3576                .ok_or("Missing required parameter: name")?;
3577            let view_type = args
3578                .get("type")
3579                .and_then(|v| v.as_str())
3580                .ok_or("Missing required parameter: type")?;
3581            // ClickUp's view-create endpoint requires grouping / divide /
3582            // sorting / filters / columns / team_sidebar / settings. Reuse
3583            // the CLI helper for the documented neutral defaults so the MCP
3584            // tool also succeeds with just name + type.
3585            let body = crate::commands::view::default_view_body(name, view_type);
3586            let resp = client
3587                .post(&format!("/v2/{}/{}/view", scope, scope_id), &body)
3588                .await
3589                .map_err(|e| e.to_string())?;
3590            let view = resp.get("view").cloned().unwrap_or(resp);
3591            Ok(compact_items(&[view], &["id", "name", "type"]))
3592        }
3593
3594        "clickup_view_update" => {
3595            let view_id = args
3596                .get("view_id")
3597                .and_then(|v| v.as_str())
3598                .ok_or("Missing required parameter: view_id")?;
3599            let name = args
3600                .get("name")
3601                .and_then(|v| v.as_str())
3602                .ok_or("Missing required parameter: name")?;
3603            let view_type = args
3604                .get("type")
3605                .and_then(|v| v.as_str())
3606                .ok_or("Missing required parameter: type")?;
3607            let body = json!({"name": name, "type": view_type});
3608            let resp = client
3609                .put(&format!("/v2/view/{}", view_id), &body)
3610                .await
3611                .map_err(|e| e.to_string())?;
3612            let view = resp.get("view").cloned().unwrap_or(resp);
3613            Ok(compact_items(&[view], &["id", "name", "type"]))
3614        }
3615
3616        "clickup_view_delete" => {
3617            let view_id = args
3618                .get("view_id")
3619                .and_then(|v| v.as_str())
3620                .ok_or("Missing required parameter: view_id")?;
3621            client
3622                .delete(&format!("/v2/view/{}", view_id))
3623                .await
3624                .map_err(|e| e.to_string())?;
3625            Ok(json!({"message": format!("View {} deleted", view_id)}))
3626        }
3627
3628        "clickup_doc_create" => {
3629            let team_id = resolve_workspace(args)?;
3630            let name = args
3631                .get("name")
3632                .and_then(|v| v.as_str())
3633                .ok_or("Missing required parameter: name")?;
3634            let mut body = json!({"name": name});
3635            if let Some(parent) = args.get("parent") {
3636                body["parent"] = parent.clone();
3637            }
3638            let resp = client
3639                .post(&format!("/v3/workspaces/{}/docs", team_id), &body)
3640                .await
3641                .map_err(|e| e.to_string())?;
3642            Ok(compact_items(&[resp], &["id", "name"]))
3643        }
3644
3645        "clickup_doc_add_page" => {
3646            let team_id = resolve_workspace(args)?;
3647            let doc_id = args
3648                .get("doc_id")
3649                .and_then(|v| v.as_str())
3650                .ok_or("Missing required parameter: doc_id")?;
3651            let name = args
3652                .get("name")
3653                .and_then(|v| v.as_str())
3654                .ok_or("Missing required parameter: name")?;
3655            let mut body = json!({"name": name});
3656            if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
3657                body["content"] = json!(content);
3658            }
3659            if let Some(subtitle) = args.get("sub_title").and_then(|v| v.as_str()) {
3660                body["sub_title"] = json!(subtitle);
3661            }
3662            if let Some(parent_page_id) = args.get("parent_page_id").and_then(|v| v.as_str()) {
3663                body["parent_page_id"] = json!(parent_page_id);
3664            }
3665            let resp = client
3666                .post(
3667                    &format!("/v3/workspaces/{}/docs/{}/pages", team_id, doc_id),
3668                    &body,
3669                )
3670                .await
3671                .map_err(|e| e.to_string())?;
3672            Ok(compact_items(&[resp], &["id", "name"]))
3673        }
3674
3675        "clickup_doc_edit_page" => {
3676            let team_id = resolve_workspace(args)?;
3677            let doc_id = args
3678                .get("doc_id")
3679                .and_then(|v| v.as_str())
3680                .ok_or("Missing required parameter: doc_id")?;
3681            let page_id = args
3682                .get("page_id")
3683                .and_then(|v| v.as_str())
3684                .ok_or("Missing required parameter: page_id")?;
3685            let mut body = json!({});
3686            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
3687                body["name"] = json!(name);
3688            }
3689            if let Some(content) = args.get("content").and_then(|v| v.as_str()) {
3690                body["content"] = json!(content);
3691            }
3692            if let Some(mode) = args.get("mode").and_then(|v| v.as_str()) {
3693                let allowed = ["replace", "append", "prepend"];
3694                if !allowed.contains(&mode) {
3695                    return Err(format!(
3696                        "Invalid mode '{}'. Valid values: {}",
3697                        mode,
3698                        allowed.join(", ")
3699                    ));
3700                }
3701                body["content_edit_mode"] = json!(mode);
3702            }
3703            let resp = client
3704                .put(
3705                    &format!(
3706                        "/v3/workspaces/{}/docs/{}/pages/{}",
3707                        team_id, doc_id, page_id
3708                    ),
3709                    &body,
3710                )
3711                .await
3712                .map_err(|e| e.to_string())?;
3713            Ok(compact_items(&[resp], &["id", "name"]))
3714        }
3715
3716        "clickup_chat_channel_create" => {
3717            let team_id = resolve_workspace(args)?;
3718            let name = args
3719                .get("name")
3720                .and_then(|v| v.as_str())
3721                .ok_or("Missing required parameter: name")?;
3722            let mut body = json!({"name": name});
3723            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
3724                body["description"] = json!(desc);
3725            }
3726            if let Some(vis) = args.get("visibility").and_then(|v| v.as_str()) {
3727                body["visibility"] = json!(vis);
3728            }
3729            let resp = client
3730                .post(&format!("/v3/workspaces/{}/chat/channels", team_id), &body)
3731                .await
3732                .map_err(|e| e.to_string())?;
3733            Ok(compact_items(&[resp], &["id", "name", "visibility"]))
3734        }
3735
3736        "clickup_chat_channel_get" => {
3737            let team_id = resolve_workspace(args)?;
3738            let channel_id = args
3739                .get("channel_id")
3740                .and_then(|v| v.as_str())
3741                .ok_or("Missing required parameter: channel_id")?;
3742            let resp = client
3743                .get(&format!(
3744                    "/v3/workspaces/{}/chat/channels/{}",
3745                    team_id, channel_id
3746                ))
3747                .await
3748                .map_err(|e| e.to_string())?;
3749            Ok(compact_items(&[resp], &["id", "name", "visibility"]))
3750        }
3751
3752        "clickup_chat_channel_update" => {
3753            let team_id = resolve_workspace(args)?;
3754            let channel_id = args
3755                .get("channel_id")
3756                .and_then(|v| v.as_str())
3757                .ok_or("Missing required parameter: channel_id")?;
3758            let mut body = json!({});
3759            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
3760                body["name"] = json!(name);
3761            }
3762            if let Some(desc) = args.get("description").and_then(|v| v.as_str()) {
3763                body["description"] = json!(desc);
3764            }
3765            let resp = client
3766                .patch(
3767                    &format!("/v3/workspaces/{}/chat/channels/{}", team_id, channel_id),
3768                    &body,
3769                )
3770                .await
3771                .map_err(|e| e.to_string())?;
3772            Ok(compact_items(&[resp], &["id", "name"]))
3773        }
3774
3775        "clickup_chat_channel_delete" => {
3776            let team_id = resolve_workspace(args)?;
3777            let channel_id = args
3778                .get("channel_id")
3779                .and_then(|v| v.as_str())
3780                .ok_or("Missing required parameter: channel_id")?;
3781            client
3782                .delete(&format!(
3783                    "/v3/workspaces/{}/chat/channels/{}",
3784                    team_id, channel_id
3785                ))
3786                .await
3787                .map_err(|e| e.to_string())?;
3788            Ok(json!({"message": format!("Channel {} deleted", channel_id)}))
3789        }
3790
3791        "clickup_chat_message_list" => {
3792            let team_id = resolve_workspace(args)?;
3793            let channel_id = args
3794                .get("channel_id")
3795                .and_then(|v| v.as_str())
3796                .ok_or("Missing required parameter: channel_id")?
3797                .to_string();
3798            let cargs = pagination::CursorArgs::from_args(args);
3799            pagination::cursor_dispatch(
3800                &cargs,
3801                client,
3802                &["data", "messages"],
3803                &["id", "content", "date"],
3804                |cursor| match cursor {
3805                    Some(c) => format!(
3806                        "/v3/workspaces/{}/chat/channels/{}/messages?cursor={}",
3807                        team_id, channel_id, c
3808                    ),
3809                    None => format!(
3810                        "/v3/workspaces/{}/chat/channels/{}/messages",
3811                        team_id, channel_id
3812                    ),
3813                },
3814            )
3815            .await
3816        }
3817
3818        "clickup_chat_message_send" => {
3819            let team_id = resolve_workspace(args)?;
3820            let channel_id = args
3821                .get("channel_id")
3822                .and_then(|v| v.as_str())
3823                .ok_or("Missing required parameter: channel_id")?;
3824            let content = args
3825                .get("content")
3826                .and_then(|v| v.as_str())
3827                .ok_or("Missing required parameter: content")?;
3828            let msg_type = args
3829                .get("type")
3830                .and_then(|v| v.as_str())
3831                .unwrap_or("message");
3832            let body = json!({"content": content, "type": msg_type});
3833            let resp = client
3834                .post(
3835                    &format!(
3836                        "/v3/workspaces/{}/chat/channels/{}/messages",
3837                        team_id, channel_id
3838                    ),
3839                    &body,
3840                )
3841                .await
3842                .map_err(|e| e.to_string())?;
3843            Ok(json!({"message": "Message sent", "id": resp.get("id")}))
3844        }
3845
3846        "clickup_chat_message_delete" => {
3847            let team_id = resolve_workspace(args)?;
3848            let message_id = args
3849                .get("message_id")
3850                .and_then(|v| v.as_str())
3851                .ok_or("Missing required parameter: message_id")?;
3852            client
3853                .delete(&format!(
3854                    "/v3/workspaces/{}/chat/messages/{}",
3855                    team_id, message_id
3856                ))
3857                .await
3858                .map_err(|e| e.to_string())?;
3859            Ok(json!({"message": format!("Message {} deleted", message_id)}))
3860        }
3861
3862        "clickup_chat_dm" => {
3863            let team_id = resolve_workspace(args)?;
3864            let user_ids = args
3865                .get("user_ids")
3866                .and_then(|v| v.as_array())
3867                .ok_or("Missing required parameter: user_ids (array of integers)")?;
3868            if user_ids.is_empty() {
3869                return Err("user_ids must contain at least one user id".to_string());
3870            }
3871            let body = json!({"user_ids": user_ids});
3872            let resp = client
3873                .post(
3874                    &format!("/v3/workspaces/{}/chat/channels/direct_message", team_id),
3875                    &body,
3876                )
3877                .await
3878                .map_err(|e| e.to_string())?;
3879            let channel = resp.get("data").cloned().unwrap_or(resp);
3880            Ok(json!({"message": "DM channel ready", "id": channel.get("id"), "channel": channel}))
3881        }
3882
3883        "clickup_webhook_create" => {
3884            let team_id = resolve_workspace(args)?;
3885            let endpoint = args
3886                .get("endpoint")
3887                .and_then(|v| v.as_str())
3888                .ok_or("Missing required parameter: endpoint")?;
3889            let events = args
3890                .get("events")
3891                .ok_or("Missing required parameter: events")?;
3892            let mut body = json!({"endpoint": endpoint, "events": events});
3893            if let Some(space_id) = args.get("space_id").and_then(|v| v.as_str()) {
3894                body["space_id"] = json!(space_id);
3895            }
3896            if let Some(folder_id) = args.get("folder_id").and_then(|v| v.as_str()) {
3897                body["folder_id"] = json!(folder_id);
3898            }
3899            if let Some(list_id) = args.get("list_id").and_then(|v| v.as_str()) {
3900                body["list_id"] = json!(list_id);
3901            }
3902            if let Some(task_id) = args.get("task_id").and_then(|v| v.as_str()) {
3903                body["task_id"] = json!(task_id);
3904            }
3905            let resp = client
3906                .post(&format!("/v2/team/{}/webhook", team_id), &body)
3907                .await
3908                .map_err(|e| e.to_string())?;
3909            let webhook = resp.get("webhook").cloned().unwrap_or(resp);
3910            Ok(compact_items(
3911                &[webhook],
3912                &["id", "endpoint", "events", "status"],
3913            ))
3914        }
3915
3916        "clickup_webhook_update" => {
3917            let webhook_id = args
3918                .get("webhook_id")
3919                .and_then(|v| v.as_str())
3920                .ok_or("Missing required parameter: webhook_id")?;
3921            let mut body = json!({});
3922            if let Some(endpoint) = args.get("endpoint").and_then(|v| v.as_str()) {
3923                body["endpoint"] = json!(endpoint);
3924            }
3925            if let Some(events) = args.get("events") {
3926                body["events"] = events.clone();
3927            }
3928            if let Some(status) = args.get("status").and_then(|v| v.as_str()) {
3929                body["status"] = json!(status);
3930            }
3931            let resp = client
3932                .put(&format!("/v2/webhook/{}", webhook_id), &body)
3933                .await
3934                .map_err(|e| e.to_string())?;
3935            let webhook = resp.get("webhook").cloned().unwrap_or(resp);
3936            Ok(compact_items(
3937                &[webhook],
3938                &["id", "endpoint", "events", "status"],
3939            ))
3940        }
3941
3942        "clickup_webhook_delete" => {
3943            let webhook_id = args
3944                .get("webhook_id")
3945                .and_then(|v| v.as_str())
3946                .ok_or("Missing required parameter: webhook_id")?;
3947            client
3948                .delete(&format!("/v2/webhook/{}", webhook_id))
3949                .await
3950                .map_err(|e| e.to_string())?;
3951            Ok(json!({"message": format!("Webhook {} deleted", webhook_id)}))
3952        }
3953
3954        "clickup_checklist_add_item" => {
3955            let checklist_id = args
3956                .get("checklist_id")
3957                .and_then(|v| v.as_str())
3958                .ok_or("Missing required parameter: checklist_id")?;
3959            let name = args
3960                .get("name")
3961                .and_then(|v| v.as_str())
3962                .ok_or("Missing required parameter: name")?;
3963            let mut body = json!({"name": name});
3964            if let Some(assignee) = args.get("assignee").and_then(|v| v.as_i64()) {
3965                body["assignee"] = json!(assignee);
3966            }
3967            let resp = client
3968                .post(
3969                    &format!("/v2/checklist/{}/checklist_item", checklist_id),
3970                    &body,
3971                )
3972                .await
3973                .map_err(|e| e.to_string())?;
3974            let item = resp.get("checklist").cloned().unwrap_or(resp);
3975            Ok(compact_items(&[item], &["id", "name"]))
3976        }
3977
3978        "clickup_checklist_update_item" => {
3979            let checklist_id = args
3980                .get("checklist_id")
3981                .and_then(|v| v.as_str())
3982                .ok_or("Missing required parameter: checklist_id")?;
3983            let item_id = args
3984                .get("item_id")
3985                .and_then(|v| v.as_str())
3986                .ok_or("Missing required parameter: item_id")?;
3987            let mut body = json!({});
3988            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
3989                body["name"] = json!(name);
3990            }
3991            if let Some(resolved) = args.get("resolved").and_then(|v| v.as_bool()) {
3992                body["resolved"] = json!(resolved);
3993            }
3994            if let Some(assignee) = args.get("assignee").and_then(|v| v.as_i64()) {
3995                body["assignee"] = json!(assignee);
3996            }
3997            client
3998                .put(
3999                    &format!("/v2/checklist/{}/checklist_item/{}", checklist_id, item_id),
4000                    &body,
4001                )
4002                .await
4003                .map_err(|e| e.to_string())?;
4004            Ok(json!({"message": format!("Checklist item {} updated", item_id)}))
4005        }
4006
4007        "clickup_checklist_delete_item" => {
4008            let checklist_id = args
4009                .get("checklist_id")
4010                .and_then(|v| v.as_str())
4011                .ok_or("Missing required parameter: checklist_id")?;
4012            let item_id = args
4013                .get("item_id")
4014                .and_then(|v| v.as_str())
4015                .ok_or("Missing required parameter: item_id")?;
4016            client
4017                .delete(&format!(
4018                    "/v2/checklist/{}/checklist_item/{}",
4019                    checklist_id, item_id
4020                ))
4021                .await
4022                .map_err(|e| e.to_string())?;
4023            Ok(json!({"message": format!("Checklist item {} deleted", item_id)}))
4024        }
4025
4026        "clickup_user_get" => {
4027            let team_id = resolve_workspace(args)?;
4028            let user_id = args
4029                .get("user_id")
4030                .and_then(|v| v.as_i64())
4031                .ok_or("Missing required parameter: user_id")?;
4032            let resp = client
4033                .get(&format!("/v2/team/{}/user/{}", team_id, user_id))
4034                .await
4035                .map_err(|e| e.to_string())?;
4036            let member = resp.get("member").cloned().unwrap_or(resp);
4037            Ok(compact_items(&[member], &["user", "role"]))
4038        }
4039
4040        "clickup_workspace_seats" => {
4041            let team_id = resolve_workspace(args)?;
4042            let resp = client
4043                .get(&format!("/v2/team/{}/seats", team_id))
4044                .await
4045                .map_err(|e| e.to_string())?;
4046            Ok(json!(resp))
4047        }
4048
4049        "clickup_workspace_plan" => {
4050            let team_id = resolve_workspace(args)?;
4051            let resp = client
4052                .get(&format!("/v2/team/{}/plan", team_id))
4053                .await
4054                .map_err(|e| e.to_string())?;
4055            Ok(json!(resp))
4056        }
4057
4058        "clickup_tag_create" => {
4059            let space_id = args
4060                .get("space_id")
4061                .and_then(|v| v.as_str())
4062                .ok_or("Missing required parameter: space_id")?;
4063            let name = args
4064                .get("name")
4065                .and_then(|v| v.as_str())
4066                .ok_or("Missing required parameter: name")?;
4067            let mut tag = json!({"name": name});
4068            if let Some(fg) = args.get("tag_fg").and_then(|v| v.as_str()) {
4069                tag["tag_fg"] = json!(fg);
4070            }
4071            if let Some(bg) = args.get("tag_bg").and_then(|v| v.as_str()) {
4072                tag["tag_bg"] = json!(bg);
4073            }
4074            let body = json!({"tag": tag});
4075            client
4076                .post(&format!("/v2/space/{}/tag", space_id), &body)
4077                .await
4078                .map_err(|e| e.to_string())?;
4079            Ok(json!({"message": format!("Tag '{}' created in space {}", name, space_id)}))
4080        }
4081
4082        "clickup_tag_update" => {
4083            let space_id = args
4084                .get("space_id")
4085                .and_then(|v| v.as_str())
4086                .ok_or("Missing required parameter: space_id")?;
4087            let tag_name = args
4088                .get("tag_name")
4089                .and_then(|v| v.as_str())
4090                .ok_or("Missing required parameter: tag_name")?;
4091            let mut tag = json!({});
4092            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
4093                tag["name"] = json!(name);
4094            }
4095            // ClickUp's tag UPDATE endpoint uses `fg_color` / `bg_color`,
4096            // unlike CREATE which uses `tag_fg` / `tag_bg`. (Quirk confirmed
4097            // against the OpenAPI spec.) Keep the input arg names matching
4098            // CREATE for caller ergonomics; translate on the wire.
4099            if let Some(fg) = args.get("tag_fg").and_then(|v| v.as_str()) {
4100                tag["fg_color"] = json!(fg);
4101            }
4102            if let Some(bg) = args.get("tag_bg").and_then(|v| v.as_str()) {
4103                tag["bg_color"] = json!(bg);
4104            }
4105            let body = json!({"tag": tag});
4106            client
4107                .put(&format!("/v2/space/{}/tag/{}", space_id, tag_name), &body)
4108                .await
4109                .map_err(|e| e.to_string())?;
4110            Ok(json!({"message": format!("Tag '{}' updated", tag_name)}))
4111        }
4112
4113        "clickup_tag_delete" => {
4114            let space_id = args
4115                .get("space_id")
4116                .and_then(|v| v.as_str())
4117                .ok_or("Missing required parameter: space_id")?;
4118            let tag_name = args
4119                .get("tag_name")
4120                .and_then(|v| v.as_str())
4121                .ok_or("Missing required parameter: tag_name")?;
4122            client
4123                .delete(&format!("/v2/space/{}/tag/{}", space_id, tag_name))
4124                .await
4125                .map_err(|e| e.to_string())?;
4126            Ok(json!({"message": format!("Tag '{}' deleted from space {}", tag_name, space_id)}))
4127        }
4128
4129        "clickup_field_unset" => {
4130            let (task_id, custom_q) = resolve_task(args, "task_id")?;
4131            let field_id = args
4132                .get("field_id")
4133                .and_then(|v| v.as_str())
4134                .ok_or("Missing required parameter: field_id")?;
4135            let path = match custom_q {
4136                Some(q) => format!("/v2/task/{}/field/{}?{}", task_id, field_id, q),
4137                None => format!("/v2/task/{}/field/{}", task_id, field_id),
4138            };
4139            client.delete(&path).await.map_err(|e| e.to_string())?;
4140            Ok(json!({"message": format!("Field {} unset on task {}", field_id, task_id)}))
4141        }
4142
4143        "clickup_attachment_list" => {
4144            let (task_id, custom_q) = resolve_task(args, "task_id")?;
4145            // ClickUp has no dedicated list-attachments endpoint. The `attachments`
4146            // array is returned inline by GET /v2/task/{id}, per the API docs.
4147            let path = match custom_q {
4148                Some(q) => format!("/v2/task/{}?{}", task_id, q),
4149                None => format!("/v2/task/{}", task_id),
4150            };
4151            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
4152            let attachments = resp
4153                .get("attachments")
4154                .and_then(|a| a.as_array())
4155                .cloned()
4156                .unwrap_or_default();
4157            Ok(compact_items(&attachments, &["id", "title", "url", "date"]))
4158        }
4159
4160        "clickup_shared_list" => {
4161            let team_id = resolve_workspace(args)?;
4162            let resp = client
4163                .get(&format!("/v2/team/{}/shared", team_id))
4164                .await
4165                .map_err(|e| e.to_string())?;
4166            Ok(json!(resp))
4167        }
4168
4169        "clickup_group_list" => {
4170            let team_id = resolve_workspace(args)?;
4171            let mut qs = format!("team_id={}", team_id);
4172            if let Some(group_ids) = args.get("group_ids").and_then(|v| v.as_array()) {
4173                for id in group_ids {
4174                    if let Some(id) = id.as_str() {
4175                        qs.push_str(&format!("&group_ids[]={}", id));
4176                    }
4177                }
4178            }
4179            let resp = client
4180                .get(&format!("/v2/group?{}", qs))
4181                .await
4182                .map_err(|e| e.to_string())?;
4183            let groups = resp
4184                .get("groups")
4185                .and_then(|g| g.as_array())
4186                .cloned()
4187                .unwrap_or_default();
4188            Ok(compact_items(&groups, &["id", "name", "members"]))
4189        }
4190
4191        "clickup_group_create" => {
4192            let team_id = resolve_workspace(args)?;
4193            let name = args
4194                .get("name")
4195                .and_then(|v| v.as_str())
4196                .ok_or("Missing required parameter: name")?;
4197            let mut body = json!({"name": name});
4198            if let Some(members) = args.get("member_ids") {
4199                body["members"] = members.clone();
4200            }
4201            let resp = client
4202                .post(&format!("/v2/team/{}/group", team_id), &body)
4203                .await
4204                .map_err(|e| e.to_string())?;
4205            Ok(compact_items(&[resp], &["id", "name"]))
4206        }
4207
4208        "clickup_group_update" => {
4209            let group_id = args
4210                .get("group_id")
4211                .and_then(|v| v.as_str())
4212                .ok_or("Missing required parameter: group_id")?;
4213            let mut body = json!({});
4214            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
4215                body["name"] = json!(name);
4216            }
4217            if let Some(add) = args.get("add_members") {
4218                body["members"] = json!({"add": add, "rem": args.get("rem_members").cloned().unwrap_or(json!([]))});
4219            } else if let Some(rem) = args.get("rem_members") {
4220                body["members"] = json!({"add": [], "rem": rem});
4221            }
4222            let resp = client
4223                .put(&format!("/v2/group/{}", group_id), &body)
4224                .await
4225                .map_err(|e| e.to_string())?;
4226            Ok(compact_items(&[resp], &["id", "name"]))
4227        }
4228
4229        "clickup_group_delete" => {
4230            let group_id = args
4231                .get("group_id")
4232                .and_then(|v| v.as_str())
4233                .ok_or("Missing required parameter: group_id")?;
4234            client
4235                .delete(&format!("/v2/group/{}", group_id))
4236                .await
4237                .map_err(|e| e.to_string())?;
4238            Ok(json!({"message": format!("Group {} deleted", group_id)}))
4239        }
4240
4241        "clickup_role_list" => {
4242            let team_id = resolve_workspace(args)?;
4243            let resp = client
4244                .get(&format!("/v2/team/{}/customroles", team_id))
4245                .await
4246                .map_err(|e| e.to_string())?;
4247            let roles = resp
4248                .get("roles")
4249                .and_then(|r| r.as_array())
4250                .cloned()
4251                .unwrap_or_default();
4252            Ok(compact_items(&roles, &["id", "name"]))
4253        }
4254
4255        "clickup_guest_get" => {
4256            let team_id = resolve_workspace(args)?;
4257            let guest_id = args
4258                .get("guest_id")
4259                .and_then(|v| v.as_i64())
4260                .ok_or("Missing required parameter: guest_id")?;
4261            let resp = client
4262                .get(&format!("/v2/team/{}/guest/{}", team_id, guest_id))
4263                .await
4264                .map_err(|e| e.to_string())?;
4265            let guest = resp.get("guest").cloned().unwrap_or(resp);
4266            Ok(compact_items(&[guest], &["user", "role"]))
4267        }
4268
4269        "clickup_task_time_in_status" => {
4270            let (task_id, custom_q) = resolve_task(args, "task_id")?;
4271            let path = match custom_q {
4272                Some(q) => format!("/v2/task/{}/time_in_status?{}", task_id, q),
4273                None => format!("/v2/task/{}/time_in_status", task_id),
4274            };
4275            let resp = client.get(&path).await.map_err(|e| e.to_string())?;
4276            Ok(resp)
4277        }
4278
4279        "clickup_task_move" => {
4280            let team_id = resolve_workspace(args)?;
4281            let task_id = args
4282                .get("task_id")
4283                .and_then(|v| v.as_str())
4284                .ok_or("Missing required parameter: task_id")?;
4285            let list_id = args
4286                .get("list_id")
4287                .and_then(|v| v.as_str())
4288                .ok_or("Missing required parameter: list_id")?;
4289            client
4290                .put(
4291                    &format!(
4292                        "/v3/workspaces/{}/tasks/{}/home_list/{}",
4293                        team_id, task_id, list_id
4294                    ),
4295                    &json!({}),
4296                )
4297                .await
4298                .map_err(|e| e.to_string())?;
4299            Ok(json!({"message": format!("Task {} moved to list {}", task_id, list_id)}))
4300        }
4301
4302        "clickup_task_set_estimate" => {
4303            // Resolve once so the message + URL both see the normalised id and
4304            // any custom-task-id query fragment lands on the v2 path.
4305            let (task_id, custom_query) = resolve_task(args, "task_id")?;
4306            let user_id = args.get("user_id").and_then(|v| v.as_i64());
4307            let time_estimate = args
4308                .get("time_estimate")
4309                .and_then(|v| v.as_i64())
4310                .ok_or("Missing required parameter: time_estimate")?;
4311
4312            if let Some(user_id) = user_id {
4313                let team_id = resolve_workspace(args)?;
4314                let body = json!({"time_estimates": [{"user_id": user_id, "time_estimate": time_estimate}]});
4315                client
4316                    .patch(
4317                        &format!(
4318                            "/v3/workspaces/{}/tasks/{}/time_estimates_by_user",
4319                            team_id, task_id
4320                        ),
4321                        &body,
4322                    )
4323                    .await
4324                    .map_err(|e| e.to_string())?;
4325            } else {
4326                let body = json!({"time_estimate": time_estimate});
4327                let path = match custom_query {
4328                    Some(q) => format!("/v2/task/{}?{}", task_id, q),
4329                    None => format!("/v2/task/{}", task_id),
4330                };
4331                client.put(&path, &body).await.map_err(|e| e.to_string())?;
4332            }
4333            Ok(json!({"message": format!("Time estimate set for task {}", task_id)}))
4334        }
4335
4336        "clickup_task_replace_estimates" => {
4337            let team_id = resolve_workspace(args)?;
4338            let task_id = args
4339                .get("task_id")
4340                .and_then(|v| v.as_str())
4341                .ok_or("Missing required parameter: task_id")?;
4342            // ClickUp's spec body is an ARRAY of {assignee, time}.
4343            // The previous shape {time_estimates: [{user_id, time_estimate}]}
4344            // had the wrong field names and the wrong wrapping, and it only
4345            // accepted a single user, silently erasing all other estimates.
4346            let estimates = args
4347                .get("estimates")
4348                .and_then(|v| v.as_array())
4349                .ok_or("Missing required parameter: estimates (array of {assignee, time})")?;
4350            if estimates.is_empty() {
4351                return Err(
4352                    "estimates must contain at least one {assignee, time} entry".to_string()
4353                );
4354            }
4355            let body = Value::Array(estimates.clone());
4356            client
4357                .put(
4358                    &format!(
4359                        "/v3/workspaces/{}/tasks/{}/time_estimates_by_user",
4360                        team_id, task_id
4361                    ),
4362                    &body,
4363                )
4364                .await
4365                .map_err(|e| e.to_string())?;
4366            Ok(json!({"message": format!("Time estimates replaced for task {}", task_id)}))
4367        }
4368
4369        "clickup_auth_check" => {
4370            client.get("/v2/user").await.map_err(|e| e.to_string())?;
4371            Ok(json!({"message": "Token valid"}))
4372        }
4373
4374        "clickup_checklist_update" => {
4375            let checklist_id = args
4376                .get("checklist_id")
4377                .and_then(|v| v.as_str())
4378                .ok_or("Missing required parameter: checklist_id")?;
4379            let mut body = json!({});
4380            if let Some(name) = args.get("name").and_then(|v| v.as_str()) {
4381                body["name"] = json!(name);
4382            }
4383            if let Some(position) = args.get("position").and_then(|v| v.as_i64()) {
4384                body["position"] = json!(position);
4385            }
4386            let resp = client
4387                .put(&format!("/v2/checklist/{}", checklist_id), &body)
4388                .await
4389                .map_err(|e| e.to_string())?;
4390            let checklist = resp.get("checklist").cloned().unwrap_or(resp);
4391            Ok(compact_items(&[checklist], &["id", "name"]))
4392        }
4393
4394        "clickup_comment_replies" => {
4395            let comment_id = args
4396                .get("comment_id")
4397                .and_then(|v| v.as_str())
4398                .ok_or("Missing required parameter: comment_id")?
4399                .to_string();
4400            let sargs = pagination::StartIdArgs::from_args(args);
4401            pagination::start_id_dispatch(
4402                &sargs,
4403                client,
4404                // `comments` first (current shape), `replies` as legacy fallback.
4405                "comments",
4406                &["id", "user", "date", "comment_text"],
4407                |start, start_id| match (start, start_id) {
4408                    (Some(s), Some(sid)) => format!(
4409                        "/v2/comment/{}/reply?start={}&start_id={}",
4410                        comment_id, s, sid
4411                    ),
4412                    _ => format!("/v2/comment/{}/reply", comment_id),
4413                },
4414            )
4415            .await
4416        }
4417
4418        "clickup_comment_reply" => {
4419            let comment_id = args
4420                .get("comment_id")
4421                .and_then(|v| v.as_str())
4422                .ok_or("Missing required parameter: comment_id")?;
4423            let text = args
4424                .get("text")
4425                .and_then(|v| v.as_str())
4426                .ok_or("Missing required parameter: text")?;
4427            let mut body = json!({"comment_text": text});
4428            if let Some(assignee) = args.get("assignee").and_then(|v| v.as_i64()) {
4429                body["assignee"] = json!(assignee);
4430            }
4431            let resp = client
4432                .post(&format!("/v2/comment/{}/reply", comment_id), &body)
4433                .await
4434                .map_err(|e| e.to_string())?;
4435            Ok(json!({"message": "Reply posted", "id": resp.get("id")}))
4436        }
4437
4438        "clickup_chat_channel_list" => {
4439            let team_id = resolve_workspace(args)?;
4440            let include_closed = args.get("include_closed").and_then(|v| v.as_bool());
4441            let cargs = pagination::CursorArgs::from_args(args);
4442            pagination::cursor_dispatch(
4443                &cargs,
4444                client,
4445                &["data", "channels"],
4446                &["id", "name", "type"],
4447                |cursor| {
4448                    let mut qs = String::new();
4449                    if let Some(ic) = include_closed {
4450                        qs.push_str(&format!("&include_closed={}", ic));
4451                    }
4452                    if let Some(c) = cursor {
4453                        qs.push_str(&format!("&cursor={}", c));
4454                    }
4455                    let query = qs.trim_start_matches('&');
4456                    if query.is_empty() {
4457                        format!("/v3/workspaces/{}/chat/channels", team_id)
4458                    } else {
4459                        format!("/v3/workspaces/{}/chat/channels?{}", team_id, query)
4460                    }
4461                },
4462            )
4463            .await
4464        }
4465
4466        "clickup_chat_channel_followers" => {
4467            let team_id = resolve_workspace(args)?;
4468            let channel_id = args
4469                .get("channel_id")
4470                .and_then(|v| v.as_str())
4471                .ok_or("Missing required parameter: channel_id")?
4472                .to_string();
4473            let cargs = pagination::CursorArgs::from_args(args);
4474            pagination::cursor_dispatch(
4475                &cargs,
4476                client,
4477                &["data"],
4478                &["id", "name", "username", "email"],
4479                |cursor| match cursor {
4480                    Some(c) => format!(
4481                        "/v3/workspaces/{}/chat/channels/{}/followers?cursor={}",
4482                        team_id, channel_id, c
4483                    ),
4484                    None => format!(
4485                        "/v3/workspaces/{}/chat/channels/{}/followers",
4486                        team_id, channel_id
4487                    ),
4488                },
4489            )
4490            .await
4491        }
4492
4493        "clickup_chat_channel_members" => {
4494            let team_id = resolve_workspace(args)?;
4495            let channel_id = args
4496                .get("channel_id")
4497                .and_then(|v| v.as_str())
4498                .ok_or("Missing required parameter: channel_id")?
4499                .to_string();
4500            let cargs = pagination::CursorArgs::from_args(args);
4501            pagination::cursor_dispatch(
4502                &cargs,
4503                client,
4504                &["data"],
4505                &["id", "name", "username", "email"],
4506                |cursor| match cursor {
4507                    Some(c) => format!(
4508                        "/v3/workspaces/{}/chat/channels/{}/members?cursor={}",
4509                        team_id, channel_id, c
4510                    ),
4511                    None => format!(
4512                        "/v3/workspaces/{}/chat/channels/{}/members",
4513                        team_id, channel_id
4514                    ),
4515                },
4516            )
4517            .await
4518        }
4519
4520        "clickup_chat_message_update" => {
4521            let team_id = resolve_workspace(args)?;
4522            let message_id = args
4523                .get("message_id")
4524                .and_then(|v| v.as_str())
4525                .ok_or("Missing required parameter: message_id")?;
4526            let text = args
4527                .get("text")
4528                .and_then(|v| v.as_str())
4529                .ok_or("Missing required parameter: text")?;
4530            let body = json!({"content": text});
4531            client
4532                .patch(
4533                    &format!("/v3/workspaces/{}/chat/messages/{}", team_id, message_id),
4534                    &body,
4535                )
4536                .await
4537                .map_err(|e| e.to_string())?;
4538            Ok(json!({"message": format!("Message {} updated", message_id)}))
4539        }
4540
4541        "clickup_chat_reaction_list" => {
4542            let team_id = resolve_workspace(args)?;
4543            let message_id = args
4544                .get("message_id")
4545                .and_then(|v| v.as_str())
4546                .ok_or("Missing required parameter: message_id")?
4547                .to_string();
4548            let cargs = pagination::CursorArgs::from_args(args);
4549            pagination::cursor_dispatch(
4550                &cargs,
4551                client,
4552                &["data"],
4553                &["reaction", "user", "date"],
4554                |cursor| match cursor {
4555                    Some(c) => format!(
4556                        "/v3/workspaces/{}/chat/messages/{}/reactions?cursor={}",
4557                        team_id, message_id, c
4558                    ),
4559                    None => format!(
4560                        "/v3/workspaces/{}/chat/messages/{}/reactions",
4561                        team_id, message_id
4562                    ),
4563                },
4564            )
4565            .await
4566        }
4567
4568        "clickup_chat_reaction_add" => {
4569            let team_id = resolve_workspace(args)?;
4570            let message_id = args
4571                .get("message_id")
4572                .and_then(|v| v.as_str())
4573                .ok_or("Missing required parameter: message_id")?;
4574            let emoji = args
4575                .get("emoji")
4576                .and_then(|v| v.as_str())
4577                .ok_or("Missing required parameter: emoji")?;
4578            let body = json!({"reaction": emoji});
4579            client
4580                .post(
4581                    &format!(
4582                        "/v3/workspaces/{}/chat/messages/{}/reactions",
4583                        team_id, message_id
4584                    ),
4585                    &body,
4586                )
4587                .await
4588                .map_err(|e| e.to_string())?;
4589            Ok(json!({"message": format!("Reaction '{}' added to message {}", emoji, message_id)}))
4590        }
4591
4592        "clickup_chat_reaction_remove" => {
4593            let team_id = resolve_workspace(args)?;
4594            let message_id = args
4595                .get("message_id")
4596                .and_then(|v| v.as_str())
4597                .ok_or("Missing required parameter: message_id")?;
4598            let emoji = args
4599                .get("emoji")
4600                .and_then(|v| v.as_str())
4601                .ok_or("Missing required parameter: emoji")?;
4602            // Emoji typically contain bytes outside the URL path's unreserved
4603            // set; percent-encode the segment so the request is well-formed.
4604            let encoded_emoji = encode_query_value(emoji);
4605            client
4606                .delete(&format!(
4607                    "/v3/workspaces/{}/chat/messages/{}/reactions/{}",
4608                    team_id, message_id, encoded_emoji
4609                ))
4610                .await
4611                .map_err(|e| e.to_string())?;
4612            Ok(
4613                json!({"message": format!("Reaction '{}' removed from message {}", emoji, message_id)}),
4614            )
4615        }
4616
4617        "clickup_chat_reply_list" => {
4618            let team_id = resolve_workspace(args)?;
4619            let message_id = args
4620                .get("message_id")
4621                .and_then(|v| v.as_str())
4622                .ok_or("Missing required parameter: message_id")?
4623                .to_string();
4624            let cargs = pagination::CursorArgs::from_args(args);
4625            pagination::cursor_dispatch(
4626                &cargs,
4627                client,
4628                &["data", "replies"],
4629                &["id", "content", "date"],
4630                |cursor| match cursor {
4631                    Some(c) => format!(
4632                        "/v3/workspaces/{}/chat/messages/{}/replies?cursor={}",
4633                        team_id, message_id, c
4634                    ),
4635                    None => format!(
4636                        "/v3/workspaces/{}/chat/messages/{}/replies",
4637                        team_id, message_id
4638                    ),
4639                },
4640            )
4641            .await
4642        }
4643
4644        "clickup_chat_reply_send" => {
4645            let team_id = resolve_workspace(args)?;
4646            let message_id = args
4647                .get("message_id")
4648                .and_then(|v| v.as_str())
4649                .ok_or("Missing required parameter: message_id")?;
4650            let text = args
4651                .get("text")
4652                .and_then(|v| v.as_str())
4653                .ok_or("Missing required parameter: text")?;
4654            let body = json!({"content": text});
4655            let resp = client
4656                .post(
4657                    &format!(
4658                        "/v3/workspaces/{}/chat/messages/{}/replies",
4659                        team_id, message_id
4660                    ),
4661                    &body,
4662                )
4663                .await
4664                .map_err(|e| e.to_string())?;
4665            Ok(json!({"message": "Reply sent", "id": resp.get("id")}))
4666        }
4667
4668        "clickup_chat_tagged_users" => {
4669            let team_id = resolve_workspace(args)?;
4670            let message_id = args
4671                .get("message_id")
4672                .and_then(|v| v.as_str())
4673                .ok_or("Missing required parameter: message_id")?
4674                .to_string();
4675            let cargs = pagination::CursorArgs::from_args(args);
4676            pagination::cursor_dispatch(
4677                &cargs,
4678                client,
4679                &["data"],
4680                &["id", "name", "username", "email"],
4681                |cursor| match cursor {
4682                    Some(c) => format!(
4683                        "/v3/workspaces/{}/chat/messages/{}/tagged_users?cursor={}",
4684                        team_id, message_id, c
4685                    ),
4686                    None => format!(
4687                        "/v3/workspaces/{}/chat/messages/{}/tagged_users",
4688                        team_id, message_id
4689                    ),
4690                },
4691            )
4692            .await
4693        }
4694
4695        "clickup_time_current" => {
4696            let team_id = resolve_workspace(args)?;
4697            let resp = client
4698                .get(&format!("/v2/team/{}/time_entries/current", team_id))
4699                .await
4700                .map_err(|e| e.to_string())?;
4701            let data = resp.get("data").cloned().unwrap_or(resp);
4702            Ok(compact_items(
4703                &[data],
4704                &["id", "task", "duration", "start", "billable"],
4705            ))
4706        }
4707
4708        "clickup_time_tags" => {
4709            let team_id = resolve_workspace(args)?;
4710            let resp = client
4711                .get(&format!("/v2/team/{}/time_entries/tags", team_id))
4712                .await
4713                .map_err(|e| e.to_string())?;
4714            let tags = resp
4715                .get("data")
4716                .and_then(|d| d.as_array())
4717                .cloned()
4718                .unwrap_or_default();
4719            Ok(compact_items(&tags, &["name"]))
4720        }
4721
4722        "clickup_time_add_tags" => {
4723            let team_id = resolve_workspace(args)?;
4724            let entry_ids = args
4725                .get("entry_ids")
4726                .and_then(|v| v.as_array())
4727                .ok_or("Missing required parameter: entry_ids")?;
4728            let tag_names = args
4729                .get("tag_names")
4730                .and_then(|v| v.as_array())
4731                .ok_or("Missing required parameter: tag_names")?;
4732            let tags: Vec<Value> = tag_names
4733                .iter()
4734                .filter_map(|n| n.as_str())
4735                .map(|n| json!({"name": n}))
4736                .collect();
4737            let body = json!({"time_entry_ids": entry_ids, "tags": tags});
4738            client
4739                .post(&format!("/v2/team/{}/time_entries/tags", team_id), &body)
4740                .await
4741                .map_err(|e| e.to_string())?;
4742            Ok(json!({"message": "Tags added to time entries"}))
4743        }
4744
4745        "clickup_time_remove_tags" => {
4746            let team_id = resolve_workspace(args)?;
4747            let entry_ids = args
4748                .get("entry_ids")
4749                .and_then(|v| v.as_array())
4750                .ok_or("Missing required parameter: entry_ids")?;
4751            let tag_names = args
4752                .get("tag_names")
4753                .and_then(|v| v.as_array())
4754                .ok_or("Missing required parameter: tag_names")?;
4755            let tags: Vec<Value> = tag_names
4756                .iter()
4757                .filter_map(|n| n.as_str())
4758                .map(|n| json!({"name": n}))
4759                .collect();
4760            let body = json!({"time_entry_ids": entry_ids, "tags": tags});
4761            client
4762                .delete_with_body(&format!("/v2/team/{}/time_entries/tags", team_id), &body)
4763                .await
4764                .map_err(|e| e.to_string())?;
4765            Ok(json!({"message": "Tags removed from time entries"}))
4766        }
4767
4768        "clickup_time_rename_tag" => {
4769            let team_id = resolve_workspace(args)?;
4770            let name = args
4771                .get("name")
4772                .and_then(|v| v.as_str())
4773                .ok_or("Missing required parameter: name")?;
4774            let new_name = args
4775                .get("new_name")
4776                .and_then(|v| v.as_str())
4777                .ok_or("Missing required parameter: new_name")?;
4778            // ClickUp's spec marks tag_bg and tag_fg as required on the
4779            // PUT /v2/team/{ws}/time_entries/tags endpoint, even when the
4780            // caller only wants to rename. Callers can repeat the existing
4781            // hex colours to leave them unchanged.
4782            let tag_bg = args
4783                .get("tag_bg")
4784                .and_then(|v| v.as_str())
4785                .ok_or("Missing required parameter: tag_bg")?;
4786            let tag_fg = args
4787                .get("tag_fg")
4788                .and_then(|v| v.as_str())
4789                .ok_or("Missing required parameter: tag_fg")?;
4790            let body =
4791                json!({"name": name, "new_name": new_name, "tag_bg": tag_bg, "tag_fg": tag_fg});
4792            client
4793                .put(&format!("/v2/team/{}/time_entries/tags", team_id), &body)
4794                .await
4795                .map_err(|e| e.to_string())?;
4796            Ok(json!({"message": format!("Tag '{}' renamed to '{}'", name, new_name)}))
4797        }
4798
4799        "clickup_time_history" => {
4800            let team_id = resolve_workspace(args)?;
4801            let timer_id = args
4802                .get("timer_id")
4803                .and_then(|v| v.as_str())
4804                .ok_or("Missing required parameter: timer_id")?;
4805            let resp = client
4806                .get(&format!(
4807                    "/v2/team/{}/time_entries/{}/history",
4808                    team_id, timer_id
4809                ))
4810                .await
4811                .map_err(|e| e.to_string())?;
4812            Ok(resp)
4813        }
4814
4815        "clickup_guest_invite" => {
4816            let team_id = resolve_workspace(args)?;
4817            let email = args
4818                .get("email")
4819                .and_then(|v| v.as_str())
4820                .ok_or("Missing required parameter: email")?;
4821            let mut body = json!({"email": email});
4822            if let Some(v) = args.get("can_edit_tags").and_then(|v| v.as_bool()) {
4823                body["can_edit_tags"] = json!(v);
4824            }
4825            if let Some(v) = args.get("can_see_time_spent").and_then(|v| v.as_bool()) {
4826                body["can_see_time_spent"] = json!(v);
4827            }
4828            if let Some(v) = args.get("can_create_views").and_then(|v| v.as_bool()) {
4829                body["can_create_views"] = json!(v);
4830            }
4831            let resp = client
4832                .post(&format!("/v2/team/{}/guest", team_id), &body)
4833                .await
4834                .map_err(|e| e.to_string())?;
4835            let guest = resp.get("guest").cloned().unwrap_or(resp);
4836            let user = guest.get("user").cloned().unwrap_or(guest);
4837            Ok(compact_items(&[user], &["id", "email"]))
4838        }
4839
4840        "clickup_guest_update" => {
4841            let team_id = resolve_workspace(args)?;
4842            let guest_id = args
4843                .get("guest_id")
4844                .and_then(|v| v.as_i64())
4845                .ok_or("Missing required parameter: guest_id")?;
4846            let mut body = json!({});
4847            if let Some(v) = args.get("can_edit_tags").and_then(|v| v.as_bool()) {
4848                body["can_edit_tags"] = json!(v);
4849            }
4850            if let Some(v) = args.get("can_see_time_spent").and_then(|v| v.as_bool()) {
4851                body["can_see_time_spent"] = json!(v);
4852            }
4853            if let Some(v) = args.get("can_create_views").and_then(|v| v.as_bool()) {
4854                body["can_create_views"] = json!(v);
4855            }
4856            client
4857                .put(&format!("/v2/team/{}/guest/{}", team_id, guest_id), &body)
4858                .await
4859                .map_err(|e| e.to_string())?;
4860            Ok(json!({"message": format!("Guest {} updated", guest_id)}))
4861        }
4862
4863        "clickup_guest_remove" => {
4864            let team_id = resolve_workspace(args)?;
4865            let guest_id = args
4866                .get("guest_id")
4867                .and_then(|v| v.as_i64())
4868                .ok_or("Missing required parameter: guest_id")?;
4869            client
4870                .delete(&format!("/v2/team/{}/guest/{}", team_id, guest_id))
4871                .await
4872                .map_err(|e| e.to_string())?;
4873            Ok(json!({"message": format!("Guest {} removed", guest_id)}))
4874        }
4875
4876        "clickup_guest_share_task" => {
4877            let task_id = args
4878                .get("task_id")
4879                .and_then(|v| v.as_str())
4880                .ok_or("Missing required parameter: task_id")?;
4881            let guest_id = args
4882                .get("guest_id")
4883                .and_then(|v| v.as_i64())
4884                .ok_or("Missing required parameter: guest_id")?;
4885            let permission = args
4886                .get("permission")
4887                .and_then(|v| v.as_str())
4888                .ok_or("Missing required parameter: permission")?;
4889            let body = json!({"permission_level": permission});
4890            client
4891                .post(&format!("/v2/task/{}/guest/{}", task_id, guest_id), &body)
4892                .await
4893                .map_err(|e| e.to_string())?;
4894            Ok(json!({"message": format!("Task {} shared with guest {}", task_id, guest_id)}))
4895        }
4896
4897        "clickup_guest_unshare_task" => {
4898            let task_id = args
4899                .get("task_id")
4900                .and_then(|v| v.as_str())
4901                .ok_or("Missing required parameter: task_id")?;
4902            let guest_id = args
4903                .get("guest_id")
4904                .and_then(|v| v.as_i64())
4905                .ok_or("Missing required parameter: guest_id")?;
4906            client
4907                .delete(&format!("/v2/task/{}/guest/{}", task_id, guest_id))
4908                .await
4909                .map_err(|e| e.to_string())?;
4910            Ok(json!({"message": format!("Guest {} unshared from task {}", guest_id, task_id)}))
4911        }
4912
4913        "clickup_guest_share_list" => {
4914            let list_id = args
4915                .get("list_id")
4916                .and_then(|v| v.as_str())
4917                .ok_or("Missing required parameter: list_id")?;
4918            let guest_id = args
4919                .get("guest_id")
4920                .and_then(|v| v.as_i64())
4921                .ok_or("Missing required parameter: guest_id")?;
4922            let permission = args
4923                .get("permission")
4924                .and_then(|v| v.as_str())
4925                .ok_or("Missing required parameter: permission")?;
4926            let body = json!({"permission_level": permission});
4927            client
4928                .post(&format!("/v2/list/{}/guest/{}", list_id, guest_id), &body)
4929                .await
4930                .map_err(|e| e.to_string())?;
4931            Ok(json!({"message": format!("List {} shared with guest {}", list_id, guest_id)}))
4932        }
4933
4934        "clickup_guest_unshare_list" => {
4935            let list_id = args
4936                .get("list_id")
4937                .and_then(|v| v.as_str())
4938                .ok_or("Missing required parameter: list_id")?;
4939            let guest_id = args
4940                .get("guest_id")
4941                .and_then(|v| v.as_i64())
4942                .ok_or("Missing required parameter: guest_id")?;
4943            client
4944                .delete(&format!("/v2/list/{}/guest/{}", list_id, guest_id))
4945                .await
4946                .map_err(|e| e.to_string())?;
4947            Ok(json!({"message": format!("Guest {} unshared from list {}", guest_id, list_id)}))
4948        }
4949
4950        "clickup_guest_share_folder" => {
4951            let folder_id = args
4952                .get("folder_id")
4953                .and_then(|v| v.as_str())
4954                .ok_or("Missing required parameter: folder_id")?;
4955            let guest_id = args
4956                .get("guest_id")
4957                .and_then(|v| v.as_i64())
4958                .ok_or("Missing required parameter: guest_id")?;
4959            let permission = args
4960                .get("permission")
4961                .and_then(|v| v.as_str())
4962                .ok_or("Missing required parameter: permission")?;
4963            let body = json!({"permission_level": permission});
4964            client
4965                .post(
4966                    &format!("/v2/folder/{}/guest/{}", folder_id, guest_id),
4967                    &body,
4968                )
4969                .await
4970                .map_err(|e| e.to_string())?;
4971            Ok(json!({"message": format!("Folder {} shared with guest {}", folder_id, guest_id)}))
4972        }
4973
4974        "clickup_guest_unshare_folder" => {
4975            let folder_id = args
4976                .get("folder_id")
4977                .and_then(|v| v.as_str())
4978                .ok_or("Missing required parameter: folder_id")?;
4979            let guest_id = args
4980                .get("guest_id")
4981                .and_then(|v| v.as_i64())
4982                .ok_or("Missing required parameter: guest_id")?;
4983            client
4984                .delete(&format!("/v2/folder/{}/guest/{}", folder_id, guest_id))
4985                .await
4986                .map_err(|e| e.to_string())?;
4987            Ok(json!({"message": format!("Guest {} unshared from folder {}", guest_id, folder_id)}))
4988        }
4989
4990        "clickup_user_invite" => {
4991            let team_id = resolve_workspace(args)?;
4992            let email = args
4993                .get("email")
4994                .and_then(|v| v.as_str())
4995                .ok_or("Missing required parameter: email")?;
4996            let mut body = json!({"email": email});
4997            if let Some(admin) = args.get("admin").and_then(|v| v.as_bool()) {
4998                body["admin"] = json!(admin);
4999            }
5000            let resp = client
5001                .post(&format!("/v2/team/{}/user", team_id), &body)
5002                .await
5003                .map_err(|e| e.to_string())?;
5004            let member = resp.get("member").cloned().unwrap_or(resp);
5005            let user = member.get("user").cloned().unwrap_or(member);
5006            Ok(compact_items(&[user], &["id", "username", "email"]))
5007        }
5008
5009        "clickup_user_update" => {
5010            let team_id = resolve_workspace(args)?;
5011            let user_id = args
5012                .get("user_id")
5013                .and_then(|v| v.as_i64())
5014                .ok_or("Missing required parameter: user_id")?;
5015            let mut body = json!({});
5016            if let Some(username) = args.get("username").and_then(|v| v.as_str()) {
5017                body["username"] = json!(username);
5018            }
5019            if let Some(admin) = args.get("admin").and_then(|v| v.as_bool()) {
5020                body["admin"] = json!(admin);
5021            }
5022            client
5023                .put(&format!("/v2/team/{}/user/{}", team_id, user_id), &body)
5024                .await
5025                .map_err(|e| e.to_string())?;
5026            Ok(json!({"message": format!("User {} updated", user_id)}))
5027        }
5028
5029        "clickup_user_remove" => {
5030            let team_id = resolve_workspace(args)?;
5031            let user_id = args
5032                .get("user_id")
5033                .and_then(|v| v.as_i64())
5034                .ok_or("Missing required parameter: user_id")?;
5035            client
5036                .delete(&format!("/v2/team/{}/user/{}", team_id, user_id))
5037                .await
5038                .map_err(|e| e.to_string())?;
5039            Ok(json!({"message": format!("User {} removed from workspace", user_id)}))
5040        }
5041
5042        "clickup_template_apply_task" => {
5043            let list_id = args
5044                .get("list_id")
5045                .and_then(|v| v.as_str())
5046                .ok_or("Missing required parameter: list_id")?;
5047            let template_id = args
5048                .get("template_id")
5049                .and_then(|v| v.as_str())
5050                .ok_or("Missing required parameter: template_id")?;
5051            let name = args
5052                .get("name")
5053                .and_then(|v| v.as_str())
5054                .ok_or("Missing required parameter: name")?;
5055            let body = json!({"name": name});
5056            let resp = client
5057                .post(
5058                    &format!("/v2/list/{}/taskTemplate/{}", list_id, template_id),
5059                    &body,
5060                )
5061                .await
5062                .map_err(|e| e.to_string())?;
5063            Ok(compact_items(&[resp], &["id", "name"]))
5064        }
5065
5066        "clickup_template_apply_list" => {
5067            let template_id = args
5068                .get("template_id")
5069                .and_then(|v| v.as_str())
5070                .ok_or("Missing required parameter: template_id")?;
5071            let name = args
5072                .get("name")
5073                .and_then(|v| v.as_str())
5074                .ok_or("Missing required parameter: name")?;
5075            let body = json!({"name": name});
5076            let path = if let Some(folder_id) = args.get("folder_id").and_then(|v| v.as_str()) {
5077                format!("/v2/folder/{}/list_template/{}", folder_id, template_id)
5078            } else if let Some(space_id) = args.get("space_id").and_then(|v| v.as_str()) {
5079                format!("/v2/space/{}/list_template/{}", space_id, template_id)
5080            } else {
5081                return Err("Provide either folder_id or space_id".to_string());
5082            };
5083            client.post(&path, &body).await.map_err(|e| e.to_string())?;
5084            Ok(json!({"message": format!("List '{}' created from template {}", name, template_id)}))
5085        }
5086
5087        "clickup_template_apply_folder" => {
5088            let space_id = args
5089                .get("space_id")
5090                .and_then(|v| v.as_str())
5091                .ok_or("Missing required parameter: space_id")?;
5092            let template_id = args
5093                .get("template_id")
5094                .and_then(|v| v.as_str())
5095                .ok_or("Missing required parameter: template_id")?;
5096            let name = args
5097                .get("name")
5098                .and_then(|v| v.as_str())
5099                .ok_or("Missing required parameter: name")?;
5100            let body = json!({"name": name});
5101            client
5102                .post(
5103                    &format!("/v2/space/{}/folder_template/{}", space_id, template_id),
5104                    &body,
5105                )
5106                .await
5107                .map_err(|e| e.to_string())?;
5108            Ok(
5109                json!({"message": format!("Folder '{}' created from template {}", name, template_id)}),
5110            )
5111        }
5112
5113        "clickup_attachment_upload" => {
5114            let (task_id, custom_q) = resolve_task(args, "task_id")?;
5115            let file_path = args
5116                .get("file_path")
5117                .and_then(|v| v.as_str())
5118                .ok_or("Missing required parameter: file_path")?;
5119            let path = match custom_q {
5120                Some(q) => format!("/v2/task/{}/attachment?{}", task_id, q),
5121                None => format!("/v2/task/{}/attachment", task_id),
5122            };
5123            let resp = client
5124                .upload_file(&path, std::path::Path::new(file_path))
5125                .await
5126                .map_err(|e| e.to_string())?;
5127            Ok(json!({"message": "File uploaded", "id": resp.get("id"), "url": resp.get("url")}))
5128        }
5129
5130        "clickup_task_type_list" => {
5131            let team_id = resolve_workspace(args)?;
5132            let resp = client
5133                .get(&format!("/v2/team/{}/custom_item", team_id))
5134                .await
5135                .map_err(|e| e.to_string())?;
5136            let items = resp
5137                .get("custom_items")
5138                .and_then(|i| i.as_array())
5139                .cloned()
5140                .unwrap_or_default();
5141            Ok(compact_items(&items, &["id", "name", "name_plural"]))
5142        }
5143
5144        "clickup_doc_get_page" => {
5145            let team_id = resolve_workspace(args)?;
5146            let doc_id = args
5147                .get("doc_id")
5148                .and_then(|v| v.as_str())
5149                .ok_or("Missing required parameter: doc_id")?;
5150            let page_id = args
5151                .get("page_id")
5152                .and_then(|v| v.as_str())
5153                .ok_or("Missing required parameter: page_id")?;
5154            let resp = client
5155                .get(&format!(
5156                    "/v3/workspaces/{}/docs/{}/pages/{}",
5157                    team_id, doc_id, page_id
5158                ))
5159                .await
5160                .map_err(|e| e.to_string())?;
5161            Ok(resp)
5162        }
5163
5164        "clickup_audit_log_query" => {
5165            let team_id = resolve_workspace(args)?;
5166            let applicability = args
5167                .get("applicability")
5168                .and_then(|v| v.as_str())
5169                .ok_or("Missing required parameter: applicability")?
5170                .to_string();
5171
5172            // Snapshot the filter-related args once so the base_body closure
5173            // can be called fresh on every iteration without re-parsing.
5174            let event_type = args
5175                .get("event_type")
5176                .and_then(|v| v.as_str())
5177                .map(String::from);
5178            let event_status = args
5179                .get("event_status")
5180                .and_then(|v| v.as_str())
5181                .map(String::from);
5182            let user_ids = args
5183                .get("user_id")
5184                .and_then(|v| v.as_array())
5185                .cloned()
5186                .unwrap_or_default();
5187            let user_emails = args
5188                .get("user_email")
5189                .and_then(|v| v.as_array())
5190                .cloned()
5191                .unwrap_or_default();
5192            let start_time = args.get("start_time").and_then(|v| v.as_i64());
5193            let end_time = args.get("end_time").and_then(|v| v.as_i64());
5194
5195            let bargs = pagination::BodyPaginationArgs::from_args(args);
5196            let path = format!("/v3/workspaces/{}/auditlogs", team_id);
5197
5198            pagination::body_pagination_dispatch(
5199                &bargs,
5200                client,
5201                &path,
5202                // v3 envelope; fallback to `events` in case ClickUp's response
5203                // uses a domain-specific key. Bare-array shape also tolerated
5204                // via extract_array's last-resort branch.
5205                &["data", "events"],
5206                // Compact fields chosen for token efficiency; the raw response
5207                // has many fields per event but these are the most useful.
5208                &["id", "eventType", "eventStatus", "userId", "eventTime"],
5209                || {
5210                    // ClickUp's audit-log body per the v3 OpenAPI spec:
5211                    //   { applicability, filter?, pagination? }
5212                    // The helper inserts the pagination block; we provide
5213                    // applicability + filter here.
5214                    let mut body = json!({"applicability": applicability});
5215                    let mut filter = serde_json::Map::new();
5216                    if let Some(t) = &event_type {
5217                        filter.insert("eventType".into(), json!(t));
5218                    }
5219                    if let Some(s) = &event_status {
5220                        filter.insert("eventStatus".into(), json!(s));
5221                    }
5222                    if !user_ids.is_empty() {
5223                        filter.insert("userId".into(), Value::Array(user_ids.clone()));
5224                    }
5225                    if !user_emails.is_empty() {
5226                        filter.insert("userEmail".into(), Value::Array(user_emails.clone()));
5227                    }
5228                    if let Some(t) = start_time {
5229                        filter.insert("startTime".into(), json!(t));
5230                    }
5231                    if let Some(t) = end_time {
5232                        filter.insert("endTime".into(), json!(t));
5233                    }
5234                    if !filter.is_empty() {
5235                        body["filter"] = Value::Object(filter);
5236                    }
5237                    body
5238                },
5239                // Per-item next-timestamp extractor. ClickUp's audit-log
5240                // entries carry the event time under `eventTime` per the
5241                // pageTimestamp / startTime / endTime naming convention.
5242                // Fall back to `timestamp` then `date` for safety against
5243                // undocumented variants.
5244                |item| {
5245                    for key in ["eventTime", "timestamp", "date"] {
5246                        if let Some(v) = item.get(key) {
5247                            if let Some(n) = v.as_i64() {
5248                                return Some(n);
5249                            }
5250                            if let Some(s) = v.as_str() {
5251                                if let Ok(n) = s.parse::<i64>() {
5252                                    return Some(n);
5253                                }
5254                            }
5255                        }
5256                    }
5257                    None
5258                },
5259            )
5260            .await
5261        }
5262
5263        "clickup_acl_update" => {
5264            let team_id = resolve_workspace(args)?;
5265            let object_type = args
5266                .get("object_type")
5267                .and_then(|v| v.as_str())
5268                .ok_or("Missing required parameter: object_type")?;
5269            let object_id = args
5270                .get("object_id")
5271                .and_then(|v| v.as_str())
5272                .ok_or("Missing required parameter: object_id")?;
5273            let mut body = json!({});
5274            if let Some(private) = args.get("private").and_then(|v| v.as_bool()) {
5275                body["private"] = json!(private);
5276            }
5277            if let Some(entries) = args.get("entries").and_then(|v| v.as_array()) {
5278                let mut normalized: Vec<Value> = Vec::with_capacity(entries.len());
5279                for (i, entry) in entries.iter().enumerate() {
5280                    let kind = entry
5281                        .get("kind")
5282                        .and_then(|v| v.as_str())
5283                        .ok_or_else(|| format!("entries[{}] missing required field 'kind'", i))?;
5284                    if kind != "user" && kind != "group" {
5285                        return Err(format!(
5286                            "entries[{}] kind must be 'user' or 'group' (got '{}')",
5287                            i, kind
5288                        ));
5289                    }
5290                    let id = entry
5291                        .get("id")
5292                        .and_then(|v| v.as_str())
5293                        .ok_or_else(|| format!("entries[{}] missing required field 'id'", i))?;
5294                    let mut out = serde_json::Map::new();
5295                    out.insert("kind".into(), json!(kind));
5296                    out.insert("id".into(), json!(id));
5297                    if let Some(level) = entry.get("permission_level").and_then(|v| v.as_i64()) {
5298                        out.insert("permission_level".into(), json!(level));
5299                    }
5300                    normalized.push(Value::Object(out));
5301                }
5302                if !normalized.is_empty() {
5303                    body["entries"] = Value::Array(normalized);
5304                }
5305            }
5306            client
5307                .patch(
5308                    &format!(
5309                        "/v3/workspaces/{}/{}/{}/acls",
5310                        team_id, object_type, object_id
5311                    ),
5312                    &body,
5313                )
5314                .await
5315                .map_err(|e| e.to_string())?;
5316            Ok(json!({"message": format!("ACL updated for {} {}", object_type, object_id)}))
5317        }
5318
5319        unknown => Err(format!("Unknown tool: {}", unknown)),
5320    }
5321}
5322
5323// ── Main server loop ──────────────────────────────────────────────────────────
5324
5325pub async fn serve(filter: filter::Filter) -> Result<(), Box<dyn std::error::Error>> {
5326    // Resolve token: CLICKUP_TOKEN env > config file
5327    let token = std::env::var("CLICKUP_TOKEN")
5328        .ok()
5329        .filter(|t| !t.is_empty())
5330        .or_else(|| {
5331            Config::load()
5332                .ok()
5333                .map(|c| c.auth.token)
5334                .filter(|t| !t.is_empty())
5335        })
5336        .ok_or("No API token. Set CLICKUP_TOKEN env var or run `clickup setup`.")?;
5337
5338    // Resolve workspace: CLICKUP_WORKSPACE env > config file
5339    let workspace_id = std::env::var("CLICKUP_WORKSPACE")
5340        .ok()
5341        .filter(|w| !w.is_empty())
5342        .or_else(|| Config::load().ok().and_then(|c| c.defaults.workspace_id));
5343
5344    let client = ClickUpClient::new(&token, 30)
5345        .map_err(|e| format!("Failed to create HTTP client: {}", e))?;
5346
5347    let stdin = tokio::io::stdin();
5348    let reader = BufReader::new(stdin);
5349    let mut lines = reader.lines();
5350
5351    let groups_str = filter
5352        .groups
5353        .as_ref()
5354        .map(|g| format!(", groups=[{}]", g.join(",")))
5355        .unwrap_or_default();
5356    let excluded_groups_str = filter
5357        .exclude_groups
5358        .as_ref()
5359        .map(|g| format!(", exclude-groups=[{}]", g.join(",")))
5360        .unwrap_or_default();
5361    eprintln!(
5362        "MCP: profile={}{}{}, exposing {}/{} tools",
5363        filter.profile.as_str(),
5364        groups_str,
5365        excluded_groups_str,
5366        filter.allowed_count(),
5367        tool_list().as_array().map(Vec::len).unwrap_or(0),
5368    );
5369
5370    while let Some(line) = lines.next_line().await? {
5371        let line = line.trim().to_string();
5372        if line.is_empty() {
5373            continue;
5374        }
5375
5376        let msg: Value = match serde_json::from_str(&line) {
5377            Ok(v) => v,
5378            Err(e) => {
5379                // Parse error — send error response with null id
5380                let resp = error_response(&Value::Null, -32700, &format!("Parse error: {}", e));
5381                println!("{}", resp);
5382                continue;
5383            }
5384        };
5385
5386        // Notifications have no id — don't respond
5387        let id = msg.get("id").cloned().unwrap_or(Value::Null);
5388        let method = msg.get("method").and_then(|v| v.as_str()).unwrap_or("");
5389
5390        if id.is_null() && method.starts_with("notifications/") {
5391            // Notification — no response needed
5392            continue;
5393        }
5394
5395        let resp = match method {
5396            "initialize" => {
5397                let version = msg
5398                    .get("params")
5399                    .and_then(|p| p.get("protocolVersion"))
5400                    .and_then(|v| v.as_str())
5401                    .unwrap_or("2024-11-05");
5402                ok_response(
5403                    &id,
5404                    json!({
5405                        "protocolVersion": version,
5406                        "capabilities": {"tools": {}},
5407                        "serverInfo": {
5408                            "name": "clickup-cli",
5409                            "version": env!("CARGO_PKG_VERSION")
5410                        }
5411                    }),
5412                )
5413            }
5414
5415            "tools/list" => ok_response(&id, json!({"tools": filtered_tool_list(&filter)})),
5416
5417            "tools/call" => {
5418                let params = msg.get("params").cloned().unwrap_or(json!({}));
5419                if let Some(response) = handle_tools_call_early(&id, &params, &filter) {
5420                    response
5421                } else {
5422                    let tool_name = params.get("name").and_then(|v| v.as_str()).unwrap_or("");
5423                    let arguments = params.get("arguments").cloned().unwrap_or(json!({}));
5424                    let result = call_tool(tool_name, &arguments, &client, &workspace_id).await;
5425                    ok_response(&id, result)
5426                }
5427            }
5428
5429            other => {
5430                // Unknown method
5431                eprintln!("Unknown method: {}", other);
5432                error_response(&id, -32601, &format!("Method not found: {}", other))
5433            }
5434        };
5435
5436        println!("{}", resp);
5437    }
5438
5439    Ok(())
5440}
5441
5442#[cfg(test)]
5443mod tests {
5444    use super::*;
5445
5446    #[test]
5447    fn task_search_query_params_include_rich_filters() {
5448        let args = json!({
5449            "space_ids": ["space 1"],
5450            "project_ids": ["folder-1"],
5451            "list_ids": ["list-1"],
5452            "statuses": ["in progress"],
5453            "assignees": ["123"],
5454            "tags": ["release train"],
5455            "include_closed": true,
5456            "subtasks": true,
5457            "parent": "parent-1",
5458            "order_by": "due_date",
5459            "reverse": true,
5460            "due_date_gt": 1700000000000_i64,
5461            "date_updated_lt": 1800000000000_i64,
5462            "custom_items": [0, 1300],
5463            "include_markdown_description": true,
5464            "custom_fields": [
5465                {"field_id": "cf-1", "operator": "IS NOT NULL"},
5466                {"field_id": "cf-2", "operator": "=", "value": "ready"}
5467            ]
5468        });
5469
5470        let params = task_search_query_params(&args);
5471
5472        assert!(params.contains(&"space_ids[]=space%201".to_string()));
5473        assert!(params.contains(&"project_ids[]=folder-1".to_string()));
5474        assert!(params.contains(&"list_ids[]=list-1".to_string()));
5475        assert!(params.contains(&"statuses[]=in%20progress".to_string()));
5476        assert!(params.contains(&"assignees[]=123".to_string()));
5477        assert!(params.contains(&"tags[]=release%20train".to_string()));
5478        assert!(params.contains(&"include_closed=true".to_string()));
5479        assert!(params.contains(&"subtasks=true".to_string()));
5480        assert!(params.contains(&"parent=parent-1".to_string()));
5481        assert!(params.contains(&"order_by=due_date".to_string()));
5482        assert!(params.contains(&"reverse=true".to_string()));
5483        assert!(params.contains(&"due_date_gt=1700000000000".to_string()));
5484        assert!(params.contains(&"date_updated_lt=1800000000000".to_string()));
5485        assert!(params.contains(&"custom_items[]=0".to_string()));
5486        assert!(params.contains(&"custom_items[]=1300".to_string()));
5487        assert!(params.contains(&"include_markdown_description=true".to_string()));
5488        assert!(
5489            params.iter().any(|param| {
5490                param.starts_with("custom_fields=%5B")
5491                    && param.contains("IS%20NOT%20NULL")
5492                    && param.contains("%22value%22%3A%22ready%22")
5493            }),
5494            "custom_fields should be serialized as one encoded JSON query value: {:?}",
5495            params
5496        );
5497    }
5498}