Skip to main content

linear_tools/
tools.rs

1//! Tool wrappers for `linear_tools` using agentic-tools-core.
2//!
3//! Each tool delegates to the corresponding method on [`LinearTools`].
4
5use crate::LinearTools;
6use crate::models::ArchiveIssueResult;
7use crate::models::CommentResult;
8use crate::models::CreateIssueResult;
9use crate::models::GetMetadataResult;
10use crate::models::IssueDetails;
11use crate::models::IssueResult;
12use crate::models::SearchResult;
13use crate::models::SetRelationResult;
14use agentic_tools_core::Tool;
15use agentic_tools_core::ToolContext;
16use agentic_tools_core::ToolError;
17use agentic_tools_core::ToolRegistry;
18use futures::future::BoxFuture;
19use schemars::JsonSchema;
20use serde::Deserialize;
21use std::sync::Arc;
22
23// ============================================================================
24// SearchIssues Tool
25// ============================================================================
26
27/// Input for `search_issues` tool.
28#[derive(Debug, Clone, Deserialize, JsonSchema)]
29pub struct SearchIssuesInput {
30    /// Full-text search term (searches title, description, and optionally comments)
31    #[serde(default)]
32    pub query: Option<String>,
33    /// Include comments in full-text search (default: true, only applies when query is provided)
34    #[serde(default)]
35    pub include_comments: Option<bool>,
36    /// Filter by priority (0=None, 1=Urgent, 2=High, 3=Normal, 4=Low)
37    #[serde(default)]
38    pub priority: Option<i32>,
39    /// Workflow state ID (UUID)
40    #[serde(default)]
41    pub state_id: Option<String>,
42    /// Assignee user ID (UUID)
43    #[serde(default)]
44    pub assignee_id: Option<String>,
45    /// Creator user ID (UUID)
46    #[serde(default)]
47    pub creator_id: Option<String>,
48    /// Team ID (UUID)
49    #[serde(default)]
50    pub team_id: Option<String>,
51    /// Project ID (UUID)
52    #[serde(default)]
53    pub project_id: Option<String>,
54    /// Only issues created after this ISO 8601 date
55    #[serde(default)]
56    pub created_after: Option<String>,
57    /// Only issues created before this ISO 8601 date
58    #[serde(default)]
59    pub created_before: Option<String>,
60    /// Only issues updated after this ISO 8601 date
61    #[serde(default)]
62    pub updated_after: Option<String>,
63    /// Only issues updated before this ISO 8601 date
64    #[serde(default)]
65    pub updated_before: Option<String>,
66    /// Page size (default 50, max 100)
67    #[serde(default)]
68    pub first: Option<i32>,
69    /// Pagination cursor
70    #[serde(default)]
71    pub after: Option<String>,
72}
73
74/// Tool for searching Linear issues.
75#[derive(Clone)]
76pub struct SearchIssuesTool {
77    linear: Arc<LinearTools>,
78}
79
80impl SearchIssuesTool {
81    pub fn new(linear: Arc<LinearTools>) -> Self {
82        Self { linear }
83    }
84}
85
86impl Tool for SearchIssuesTool {
87    type Input = SearchIssuesInput;
88    type Output = SearchResult;
89    const NAME: &'static str = "linear_search_issues";
90    const DESCRIPTION: &'static str = "Search Linear issues using full-text search and/or filters";
91
92    fn call(
93        &self,
94        input: Self::Input,
95        _ctx: &ToolContext,
96    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
97        let linear = Arc::clone(&self.linear);
98        Box::pin(async move {
99            linear
100                .search_issues(
101                    input.query,
102                    input.include_comments,
103                    input.priority,
104                    input.state_id,
105                    input.assignee_id,
106                    input.creator_id,
107                    input.team_id,
108                    input.project_id,
109                    input.created_after,
110                    input.created_before,
111                    input.updated_after,
112                    input.updated_before,
113                    input.first,
114                    input.after,
115                )
116                .await
117                .map_err(|e| map_anyhow_to_tool_error(&e))
118        })
119    }
120}
121
122// ============================================================================
123// ReadIssue Tool
124// ============================================================================
125
126/// Input for `read_issue` tool.
127#[derive(Debug, Clone, Deserialize, JsonSchema)]
128pub struct ReadIssueInput {
129    /// Issue ID, identifier (e.g., ENG-245), or URL
130    pub issue: String,
131}
132
133/// Tool for reading a single Linear issue.
134#[derive(Clone)]
135pub struct ReadIssueTool {
136    linear: Arc<LinearTools>,
137}
138
139impl ReadIssueTool {
140    pub fn new(linear: Arc<LinearTools>) -> Self {
141        Self { linear }
142    }
143}
144
145impl Tool for ReadIssueTool {
146    type Input = ReadIssueInput;
147    type Output = IssueDetails;
148    const NAME: &'static str = "linear_read_issue";
149    const DESCRIPTION: &'static str = "Read a Linear issue by ID, identifier (e.g., ENG-245), or URL. Returns issue details and description only; comments are separate. For a full ticket read, also call linear_get_issue_comments until has_more=false.";
150
151    fn call(
152        &self,
153        input: Self::Input,
154        _ctx: &ToolContext,
155    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
156        let linear = Arc::clone(&self.linear);
157        Box::pin(async move {
158            linear
159                .read_issue(input.issue)
160                .await
161                .map_err(|e| map_anyhow_to_tool_error(&e))
162        })
163    }
164}
165
166// ============================================================================
167// CreateIssue Tool
168// ============================================================================
169
170/// Input for `create_issue` tool.
171#[derive(Debug, Clone, Deserialize, JsonSchema)]
172pub struct CreateIssueInput {
173    /// Team ID (UUID) to create the issue in
174    pub team_id: String,
175    /// Issue title
176    pub title: String,
177    /// Issue description (markdown supported)
178    #[serde(default)]
179    pub description: Option<String>,
180    /// Priority (0=None, 1=Urgent, 2=High, 3=Normal, 4=Low)
181    #[serde(default)]
182    pub priority: Option<i32>,
183    /// Assignee user ID (UUID)
184    #[serde(default)]
185    pub assignee_id: Option<String>,
186    /// Project ID (UUID)
187    #[serde(default)]
188    pub project_id: Option<String>,
189    /// Workflow state ID (UUID)
190    #[serde(default)]
191    pub state_id: Option<String>,
192    /// Parent issue ID (UUID) for sub-issues
193    #[serde(default)]
194    pub parent_id: Option<String>,
195    /// Label IDs (UUIDs)
196    #[serde(default)]
197    pub label_ids: Vec<String>,
198}
199
200/// Tool for creating a new Linear issue.
201#[derive(Clone)]
202pub struct CreateIssueTool {
203    linear: Arc<LinearTools>,
204}
205
206impl CreateIssueTool {
207    pub fn new(linear: Arc<LinearTools>) -> Self {
208        Self { linear }
209    }
210}
211
212impl Tool for CreateIssueTool {
213    type Input = CreateIssueInput;
214    type Output = CreateIssueResult;
215    const NAME: &'static str = "linear_create_issue";
216    const DESCRIPTION: &'static str = "Create a new Linear issue in a team";
217
218    fn call(
219        &self,
220        input: Self::Input,
221        _ctx: &ToolContext,
222    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
223        let linear = Arc::clone(&self.linear);
224        Box::pin(async move {
225            linear
226                .create_issue(
227                    input.team_id,
228                    input.title,
229                    input.description,
230                    input.priority,
231                    input.assignee_id,
232                    input.project_id,
233                    input.state_id,
234                    input.parent_id,
235                    input.label_ids,
236                )
237                .await
238                .map_err(|e| map_anyhow_to_tool_error(&e))
239        })
240    }
241}
242
243// ============================================================================
244// AddComment Tool
245// ============================================================================
246
247/// Input for `add_comment` tool.
248#[derive(Debug, Clone, Deserialize, JsonSchema)]
249pub struct AddCommentInput {
250    /// Issue ID, identifier (e.g., ENG-245), or URL
251    pub issue: String,
252    /// Comment body (markdown supported)
253    pub body: String,
254    /// Parent comment ID for replies (UUID)
255    #[serde(default)]
256    pub parent_id: Option<String>,
257}
258
259/// Tool for adding a comment to a Linear issue.
260#[derive(Clone)]
261pub struct AddCommentTool {
262    linear: Arc<LinearTools>,
263}
264
265impl AddCommentTool {
266    pub fn new(linear: Arc<LinearTools>) -> Self {
267        Self { linear }
268    }
269}
270
271impl Tool for AddCommentTool {
272    type Input = AddCommentInput;
273    type Output = CommentResult;
274    const NAME: &'static str = "linear_add_comment";
275    const DESCRIPTION: &'static str = "Add a comment to a Linear issue";
276
277    fn call(
278        &self,
279        input: Self::Input,
280        _ctx: &ToolContext,
281    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
282        let linear = Arc::clone(&self.linear);
283        Box::pin(async move {
284            linear
285                .add_comment(input.issue, input.body, input.parent_id)
286                .await
287                .map_err(|e| map_anyhow_to_tool_error(&e))
288        })
289    }
290}
291
292// ============================================================================
293// GetIssueComments Tool
294// ============================================================================
295
296/// Input for `get_issue_comments` tool.
297#[derive(Debug, Clone, Deserialize, JsonSchema)]
298pub struct GetIssueCommentsInput {
299    /// Issue ID, identifier (e.g., ENG-245), or URL
300    pub issue: String,
301}
302
303/// Tool for fetching comments on a Linear issue with implicit pagination.
304#[derive(Clone)]
305pub struct GetIssueCommentsTool {
306    linear: Arc<LinearTools>,
307}
308
309impl GetIssueCommentsTool {
310    pub fn new(linear: Arc<LinearTools>) -> Self {
311        Self { linear }
312    }
313}
314
315impl Tool for GetIssueCommentsTool {
316    type Input = GetIssueCommentsInput;
317    type Output = crate::models::CommentsResult;
318    const NAME: &'static str = "linear_get_issue_comments";
319    const DESCRIPTION: &'static str = "Get comments on a Linear issue (up to 10 per call) with implicit pagination. Repeat calls with the same issue until has_more=false; another call after completion restarts from the beginning.";
320
321    fn call(
322        &self,
323        input: Self::Input,
324        _ctx: &ToolContext,
325    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
326        let linear = Arc::clone(&self.linear);
327        Box::pin(async move {
328            linear
329                .get_issue_comments(input.issue)
330                .await
331                .map_err(|e| map_anyhow_to_tool_error(&e))
332        })
333    }
334}
335
336// ============================================================================
337// ArchiveIssue Tool
338// ============================================================================
339
340/// Input for `archive_issue` tool.
341#[derive(Debug, Clone, Deserialize, JsonSchema)]
342pub struct ArchiveIssueInput {
343    /// Issue ID, identifier (e.g., ENG-245), or URL
344    pub issue: String,
345}
346
347/// Tool for archiving a Linear issue.
348#[derive(Clone)]
349pub struct ArchiveIssueTool {
350    linear: Arc<LinearTools>,
351}
352
353impl ArchiveIssueTool {
354    pub fn new(linear: Arc<LinearTools>) -> Self {
355        Self { linear }
356    }
357}
358
359impl Tool for ArchiveIssueTool {
360    type Input = ArchiveIssueInput;
361    type Output = ArchiveIssueResult;
362    const NAME: &'static str = "linear_archive_issue";
363    const DESCRIPTION: &'static str =
364        "Archive a Linear issue by ID, identifier (e.g., ENG-245), or URL";
365
366    fn call(
367        &self,
368        input: Self::Input,
369        _ctx: &ToolContext,
370    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
371        let linear = Arc::clone(&self.linear);
372        Box::pin(async move {
373            linear
374                .archive_issue(input.issue)
375                .await
376                .map_err(|e| map_anyhow_to_tool_error(&e))
377        })
378    }
379}
380
381// ============================================================================
382// UpdateIssue Tool
383// ============================================================================
384
385/// Input for updating an existing Linear issue
386#[derive(Debug, Clone, Deserialize, JsonSchema)]
387pub struct UpdateIssueInput {
388    /// Issue identifier (UUID, key like ENG-245, or Linear URL)
389    pub issue: String,
390    /// New title for the issue
391    #[serde(default)]
392    pub title: Option<String>,
393    /// New description (markdown supported)
394    #[serde(default)]
395    pub description: Option<String>,
396    /// Priority: 0=None, 1=Urgent, 2=High, 3=Medium, 4=Low
397    #[serde(default)]
398    pub priority: Option<i32>,
399    /// Assignee user ID (UUID)
400    #[serde(default)]
401    pub assignee_id: Option<String>,
402    /// Workflow state ID (UUID)
403    #[serde(default)]
404    pub state_id: Option<String>,
405    /// Project ID (UUID)
406    #[serde(default)]
407    pub project_id: Option<String>,
408    /// Parent issue ID (UUID) for sub-issues
409    #[serde(default)]
410    pub parent_id: Option<String>,
411    /// Replace all labels with these IDs (overrides existing)
412    #[serde(default)]
413    pub label_ids: Option<Vec<String>>,
414    /// Add these label IDs (incremental)
415    #[serde(default)]
416    pub added_label_ids: Option<Vec<String>>,
417    /// Remove these label IDs (incremental)
418    #[serde(default)]
419    pub removed_label_ids: Option<Vec<String>>,
420    /// Due date in ISO 8601 format (YYYY-MM-DD)
421    #[serde(default)]
422    pub due_date: Option<String>,
423}
424
425/// Tool for updating an existing Linear issue.
426#[derive(Clone)]
427pub struct UpdateIssueTool {
428    linear: Arc<LinearTools>,
429}
430
431impl UpdateIssueTool {
432    pub fn new(linear: Arc<LinearTools>) -> Self {
433        Self { linear }
434    }
435}
436
437impl Tool for UpdateIssueTool {
438    type Input = UpdateIssueInput;
439    type Output = IssueResult;
440    const NAME: &'static str = "linear_update_issue";
441    const DESCRIPTION: &'static str = "Update an existing Linear issue. Use linear_get_metadata to look up user IDs, state IDs, project IDs, and label IDs.";
442
443    fn call(
444        &self,
445        input: Self::Input,
446        _ctx: &ToolContext,
447    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
448        let linear = Arc::clone(&self.linear);
449        Box::pin(async move {
450            linear
451                .update_issue(
452                    input.issue,
453                    input.title,
454                    input.description,
455                    input.priority,
456                    input.assignee_id,
457                    input.state_id,
458                    input.project_id,
459                    input.parent_id,
460                    input.label_ids,
461                    input.added_label_ids,
462                    input.removed_label_ids,
463                    input.due_date,
464                )
465                .await
466                .map_err(|e| map_anyhow_to_tool_error(&e))
467        })
468    }
469}
470
471// ============================================================================
472// SetRelation Tool
473// ============================================================================
474
475/// Input for setting or removing an issue relation
476#[derive(Debug, Clone, Deserialize, JsonSchema)]
477pub struct SetRelationInput {
478    /// Source issue identifier (UUID, key like ENG-245, or URL)
479    pub issue: String,
480    /// Related issue identifier (UUID, key like ENG-245, or URL)
481    pub related_issue: String,
482    /// Relation type: "blocks", "duplicate", "related". Null/omitted to remove relation.
483    #[serde(default)]
484    pub relation_type: Option<String>,
485}
486
487/// Tool for setting or removing issue relations.
488#[derive(Clone)]
489pub struct SetRelationTool {
490    linear: Arc<LinearTools>,
491}
492
493impl SetRelationTool {
494    pub fn new(linear: Arc<LinearTools>) -> Self {
495        Self { linear }
496    }
497}
498
499impl Tool for SetRelationTool {
500    type Input = SetRelationInput;
501    type Output = SetRelationResult;
502    const NAME: &'static str = "linear_set_relation";
503    const DESCRIPTION: &'static str = "Set or remove a relation between two issues. Provide relation_type to create (blocks/duplicate/related), or omit/null to remove any existing relation.";
504
505    fn call(
506        &self,
507        input: Self::Input,
508        _ctx: &ToolContext,
509    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
510        let linear = Arc::clone(&self.linear);
511        Box::pin(async move {
512            linear
513                .set_relation(input.issue, input.related_issue, input.relation_type)
514                .await
515                .map_err(|e| map_anyhow_to_tool_error(&e))
516        })
517    }
518}
519
520// ============================================================================
521// GetMetadata Tool
522// ============================================================================
523
524/// Input for `get_metadata` tool.
525#[derive(Debug, Clone, Deserialize, JsonSchema)]
526pub struct GetMetadataInput {
527    /// Kind of metadata to retrieve
528    pub kind: crate::models::MetadataKind,
529    /// Optional search string (case-insensitive name match)
530    #[serde(default)]
531    pub search: Option<String>,
532    /// Optional team ID to filter by (relevant for `workflow_states` and labels)
533    #[serde(default)]
534    pub team_id: Option<String>,
535    /// Maximum number of results (default: 50)
536    #[serde(default)]
537    pub first: Option<i32>,
538    /// Pagination cursor for next page
539    #[serde(default)]
540    pub after: Option<String>,
541}
542
543/// Tool for looking up Linear metadata (users, teams, projects, workflow states, labels).
544#[derive(Clone)]
545pub struct GetMetadataTool {
546    linear: Arc<LinearTools>,
547}
548
549impl GetMetadataTool {
550    pub fn new(linear: Arc<LinearTools>) -> Self {
551        Self { linear }
552    }
553}
554
555impl Tool for GetMetadataTool {
556    type Input = GetMetadataInput;
557    type Output = GetMetadataResult;
558    const NAME: &'static str = "linear_get_metadata";
559    const DESCRIPTION: &'static str = "Look up Linear metadata: users, teams, projects, workflow states, or labels. Use this to discover IDs for filtering and updating issues.";
560
561    fn call(
562        &self,
563        input: Self::Input,
564        _ctx: &ToolContext,
565    ) -> BoxFuture<'static, Result<Self::Output, ToolError>> {
566        let linear = Arc::clone(&self.linear);
567        Box::pin(async move {
568            linear
569                .get_metadata(
570                    input.kind,
571                    input.search,
572                    input.team_id,
573                    input.first,
574                    input.after,
575                )
576                .await
577                .map_err(|e| map_anyhow_to_tool_error(&e))
578        })
579    }
580}
581
582// ============================================================================
583// Registry Builder
584// ============================================================================
585
586/// Build a `ToolRegistry` containing all `linear_tools` tools.
587pub fn build_registry(linear: Arc<LinearTools>) -> ToolRegistry {
588    ToolRegistry::builder()
589        .register::<SearchIssuesTool, ()>(SearchIssuesTool::new(Arc::clone(&linear)))
590        .register::<ReadIssueTool, ()>(ReadIssueTool::new(Arc::clone(&linear)))
591        .register::<CreateIssueTool, ()>(CreateIssueTool::new(Arc::clone(&linear)))
592        .register::<AddCommentTool, ()>(AddCommentTool::new(Arc::clone(&linear)))
593        .register::<GetIssueCommentsTool, ()>(GetIssueCommentsTool::new(Arc::clone(&linear)))
594        .register::<ArchiveIssueTool, ()>(ArchiveIssueTool::new(Arc::clone(&linear)))
595        .register::<UpdateIssueTool, ()>(UpdateIssueTool::new(Arc::clone(&linear)))
596        .register::<SetRelationTool, ()>(SetRelationTool::new(Arc::clone(&linear)))
597        .register::<GetMetadataTool, ()>(GetMetadataTool::new(linear))
598        .finish()
599}
600
601// ============================================================================
602// Error Conversion
603// ============================================================================
604
605/// Map `anyhow::Error` to `agentic_tools_core::ToolError` based on error message patterns.
606fn map_anyhow_to_tool_error(e: &anyhow::Error) -> ToolError {
607    let msg = e.to_string();
608    let lc = msg.to_lowercase();
609    if lc.contains("permission") || lc.contains("401") || lc.contains("403") {
610        ToolError::Permission(msg)
611    } else if lc.contains("not found") || lc.contains("404") {
612        ToolError::NotFound(msg)
613    } else if lc.contains("invalid") || lc.contains("bad request") {
614        ToolError::InvalidInput(msg)
615    } else if lc.contains("timeout") || lc.contains("network") || lc.contains("rate limit") {
616        ToolError::External(msg)
617    } else {
618        ToolError::Internal(msg)
619    }
620}