Skip to main content

linear_tools/
lib.rs

1pub mod http;
2pub mod models;
3pub mod tools;
4
5/// Test support utilities (for use in tests)
6#[doc(hidden)]
7pub mod test_support;
8
9use agentic_config::types::LinearServiceConfig;
10use agentic_tools_utils::pagination::PaginationCache;
11use agentic_tools_utils::pagination::paginate_slice;
12use anyhow::Context;
13use anyhow::Result;
14use cynic::MutationBuilder;
15use cynic::QueryBuilder;
16use http::LinearClient;
17use linear_queries::CommentCreateArguments;
18use linear_queries::CommentCreateInput;
19use linear_queries::CommentCreateMutation;
20use linear_queries::DateComparator;
21use linear_queries::IdComparator;
22use linear_queries::IssueArchiveArguments;
23use linear_queries::IssueArchiveMutation;
24use linear_queries::IssueBranchNameByIdArguments;
25use linear_queries::IssueBranchNameByIdQuery;
26use linear_queries::IssueByIdArguments;
27use linear_queries::IssueByIdQuery;
28use linear_queries::IssueCommentsArguments;
29use linear_queries::IssueCommentsQuery;
30use linear_queries::IssueCreateArguments;
31use linear_queries::IssueCreateInput;
32use linear_queries::IssueCreateMutation;
33use linear_queries::IssueFilter;
34use linear_queries::IssueRelationCreateArguments;
35use linear_queries::IssueRelationCreateInput;
36use linear_queries::IssueRelationCreateMutation;
37use linear_queries::IssueRelationDeleteArguments;
38use linear_queries::IssueRelationDeleteMutation;
39use linear_queries::IssueRelationType;
40use linear_queries::IssueRelationsArguments;
41use linear_queries::IssueRelationsQuery;
42use linear_queries::IssueUpdateArguments;
43use linear_queries::IssueUpdateInput;
44use linear_queries::IssueUpdateMutation;
45use linear_queries::IssuesArguments;
46use linear_queries::IssuesBranchNameQuery;
47use linear_queries::IssuesQuery;
48use linear_queries::NullableNumberComparator;
49use linear_queries::NullableProjectFilter;
50use linear_queries::NullableUserFilter;
51use linear_queries::NumberComparator;
52use linear_queries::SearchIssuesArguments;
53use linear_queries::SearchIssuesQuery;
54use linear_queries::StringComparator;
55use linear_queries::TeamFilter;
56use linear_queries::WorkflowStateFilter;
57use linear_queries::scalars::DateTimeOrDuration;
58use regex::Regex;
59use std::sync::Arc;
60
61// Re-export agentic-tools types for MCP server usage
62pub use tools::build_registry;
63
64/// Parse identifier "ENG-245" from plain text or URL; normalize to uppercase.
65/// Returns (`team_key`, number) if a valid identifier is found.
66fn parse_identifier(input: &str) -> Option<(String, i32)> {
67    let upper = input.to_uppercase();
68    #[expect(clippy::expect_used, reason = "regex literal is valid by construction")]
69    let re = Regex::new(r"([A-Z]{2,10})-(\d{1,10})").expect("valid issue identifier regex");
70    if let Some(caps) = re.captures(&upper) {
71        let key = caps.get(1)?.as_str().to_string();
72        let num_str = caps.get(2)?.as_str();
73        let number: i32 = num_str.parse().ok()?;
74        return Some((key, number));
75    }
76    None
77}
78
79fn issue_filter_for_team_number(team_key: String, number: i32) -> IssueFilter {
80    IssueFilter {
81        team: Some(TeamFilter {
82            key: Some(StringComparator {
83                eq: Some(team_key),
84                ..Default::default()
85            }),
86            ..Default::default()
87        }),
88        number: Some(NumberComparator {
89            eq: Some(f64::from(number)),
90            ..Default::default()
91        }),
92        ..Default::default()
93    }
94}
95
96const COMMENTS_PAGE_SIZE: usize = 10;
97const ISSUE_COMMENTS_FETCH_PAGE_SIZE: i32 = 50;
98const ISSUE_COMMENTS_MAX_PAGES: usize = 100;
99
100#[derive(Clone)]
101pub struct LinearTools {
102    api_key: Option<String>,
103    config: LinearServiceConfig,
104    comments_cache: Arc<PaginationCache<models::CommentSummary, String>>,
105}
106
107impl LinearTools {
108    pub fn new() -> Self {
109        Self::with_config(LinearServiceConfig::default())
110    }
111
112    pub fn with_config(config: LinearServiceConfig) -> Self {
113        Self {
114            api_key: std::env::var("LINEAR_API_KEY").ok(),
115            config,
116            comments_cache: Arc::new(PaginationCache::new()),
117        }
118    }
119
120    pub fn config(&self) -> &LinearServiceConfig {
121        &self.config
122    }
123
124    fn client(&self) -> Result<LinearClient> {
125        LinearClient::new(self.api_key.clone(), &self.config)
126            .context("internal: failed to create Linear client")
127    }
128
129    fn resolve_issue_id(input: &str) -> IssueIdentifier {
130        // Try to parse as identifier (handles lowercase and URLs)
131        if let Some((key, number)) = parse_identifier(input) {
132            return IssueIdentifier::Identifier(format!("{key}-{number}"));
133        }
134        // Fallback: treat as ID/UUID
135        IssueIdentifier::Id(input.to_string())
136    }
137
138    /// Resolve an issue identifier (UUID, ENG-245, or URL) to a UUID.
139    /// For identifiers, queries Linear to find the matching issue.
140    async fn resolve_to_issue_id(&self, client: &LinearClient, input: &str) -> Result<String> {
141        match Self::resolve_issue_id(input) {
142            IssueIdentifier::Id(id) => Ok(id),
143            IssueIdentifier::Identifier(ident) => {
144                let (team_key, number) = parse_identifier(&ident)
145                    .ok_or_else(|| anyhow::anyhow!("not found: Issue {ident} not found"))?;
146                let filter = issue_filter_for_team_number(team_key, number);
147                let op = IssuesQuery::build(IssuesArguments {
148                    first: Some(1),
149                    after: None,
150                    filter: Some(filter),
151                });
152                let resp = client.run(op).await?;
153                let data = http::extract_data(resp)?;
154                let issue = data
155                    .issues
156                    .nodes
157                    .into_iter()
158                    .next()
159                    .ok_or_else(|| anyhow::anyhow!("not found: Issue {ident} not found"))?;
160                Ok(issue.id.inner().to_string())
161            }
162        }
163    }
164}
165
166impl Default for LinearTools {
167    fn default() -> Self {
168        Self::new()
169    }
170}
171
172enum IssueIdentifier {
173    Id(String),
174    Identifier(String),
175}
176
177// Note: Error handling moved to tools.rs with map_anyhow_to_tool_error.
178// HTTP error enrichment via summarize_reqwest_error is available for use in tools.rs if needed.
179
180// ============================================================================
181// From impls: GraphQL types -> tool model types
182// ============================================================================
183
184impl From<linear_queries::User> for models::UserRef {
185    fn from(u: linear_queries::User) -> Self {
186        let name = if u.display_name.is_empty() {
187            u.name
188        } else {
189            u.display_name
190        };
191        Self {
192            id: u.id.inner().to_string(),
193            name,
194            email: u.email,
195        }
196    }
197}
198
199impl From<linear_queries::Team> for models::TeamRef {
200    fn from(t: linear_queries::Team) -> Self {
201        Self {
202            id: t.id.inner().to_string(),
203            key: t.key,
204            name: t.name,
205        }
206    }
207}
208
209impl From<linear_queries::WorkflowState> for models::WorkflowStateRef {
210    fn from(s: linear_queries::WorkflowState) -> Self {
211        Self {
212            id: s.id.inner().to_string(),
213            name: s.name,
214            state_type: s.state_type,
215        }
216    }
217}
218
219impl From<linear_queries::Project> for models::ProjectRef {
220    fn from(p: linear_queries::Project) -> Self {
221        Self {
222            id: p.id.inner().to_string(),
223            name: p.name,
224        }
225    }
226}
227
228impl From<linear_queries::ParentIssue> for models::ParentIssueRef {
229    fn from(p: linear_queries::ParentIssue) -> Self {
230        Self {
231            id: p.id.inner().to_string(),
232            identifier: p.identifier,
233        }
234    }
235}
236
237impl From<linear_queries::Issue> for models::IssueSummary {
238    fn from(i: linear_queries::Issue) -> Self {
239        Self {
240            id: i.id.inner().to_string(),
241            identifier: i.identifier,
242            title: i.title,
243            url: i.url,
244            team: i.team.into(),
245            state: i.state.map(Into::into),
246            assignee: i.assignee.map(Into::into),
247            creator: i.creator.map(Into::into),
248            project: i.project.map(Into::into),
249            priority: i.priority as i32,
250            priority_label: i.priority_label,
251            label_ids: i.label_ids,
252            due_date: i.due_date.map(|d| d.0),
253            created_at: i.created_at.0,
254            updated_at: i.updated_at.0,
255        }
256    }
257}
258
259impl From<linear_queries::IssueSearchResult> for models::IssueSummary {
260    fn from(i: linear_queries::IssueSearchResult) -> Self {
261        Self {
262            id: i.id.inner().to_string(),
263            identifier: i.identifier,
264            title: i.title,
265            url: i.url,
266            team: i.team.into(),
267            state: Some(i.state.into()),
268            assignee: i.assignee.map(Into::into),
269            creator: i.creator.map(Into::into),
270            project: i.project.map(Into::into),
271            priority: i.priority as i32,
272            priority_label: i.priority_label,
273            label_ids: i.label_ids,
274            due_date: i.due_date.map(|d| d.0),
275            created_at: i.created_at.0,
276            updated_at: i.updated_at.0,
277        }
278    }
279}
280
281// Removed universal-tool-core macros; Tool impls live in tools.rs
282impl LinearTools {
283    /// Fetch Linear Issue.branchName (UUID, ENG-123, or Linear issue URL).
284    pub async fn read_issue_branch_name(&self, issue: String) -> Result<String> {
285        let client = self.client()?;
286
287        match Self::resolve_issue_id(&issue) {
288            IssueIdentifier::Id(id) => {
289                let op = IssueBranchNameByIdQuery::build(IssueBranchNameByIdArguments { id });
290                let resp = client.run(op).await?;
291                let data = http::extract_data(resp)?;
292                let issue = data
293                    .issue
294                    .ok_or_else(|| anyhow::anyhow!("not found: Issue not found"))?;
295                Ok(issue.branch_name)
296            }
297            IssueIdentifier::Identifier(ident) => {
298                let (team_key, number) = parse_identifier(&ident)
299                    .ok_or_else(|| anyhow::anyhow!("not found: Issue {ident} not found"))?;
300
301                let filter = issue_filter_for_team_number(team_key, number);
302
303                let op = IssuesBranchNameQuery::build(IssuesArguments {
304                    first: Some(1),
305                    after: None,
306                    filter: Some(filter),
307                });
308
309                let resp = client.run(op).await?;
310                let data = http::extract_data(resp)?;
311                let issue = data
312                    .issues
313                    .nodes
314                    .into_iter()
315                    .next()
316                    .ok_or_else(|| anyhow::anyhow!("not found: Issue {ident} not found"))?;
317
318                Ok(issue.branch_name)
319            }
320        }
321    }
322
323    /// Search Linear issues with full-text search or filters
324    #[expect(clippy::too_many_arguments)]
325    pub async fn search_issues(
326        &self,
327        query: Option<String>,
328        include_comments: Option<bool>,
329        priority: Option<i32>,
330        state_id: Option<String>,
331        assignee_id: Option<String>,
332        creator_id: Option<String>,
333        team_id: Option<String>,
334        project_id: Option<String>,
335        created_after: Option<String>,
336        created_before: Option<String>,
337        updated_after: Option<String>,
338        updated_before: Option<String>,
339        first: Option<i32>,
340        after: Option<String>,
341    ) -> Result<models::SearchResult> {
342        let client = self.client()?;
343
344        // Build filters (no title filter - full-text search handles query)
345        let mut filter = IssueFilter::default();
346        if let Some(p) = priority {
347            filter.priority = Some(NullableNumberComparator {
348                eq: Some(f64::from(p)),
349                ..Default::default()
350            });
351        }
352        if let Some(id) = state_id {
353            filter.state = Some(WorkflowStateFilter {
354                id: Some(IdComparator {
355                    eq: Some(cynic::Id::new(id)),
356                }),
357                ..Default::default()
358            });
359        }
360        if let Some(id) = assignee_id {
361            filter.assignee = Some(NullableUserFilter {
362                id: Some(IdComparator {
363                    eq: Some(cynic::Id::new(id)),
364                }),
365            });
366        }
367        if let Some(id) = creator_id {
368            filter.creator = Some(NullableUserFilter {
369                id: Some(IdComparator {
370                    eq: Some(cynic::Id::new(id)),
371                }),
372            });
373        }
374        if let Some(id) = team_id {
375            filter.team = Some(TeamFilter {
376                id: Some(IdComparator {
377                    eq: Some(cynic::Id::new(id)),
378                }),
379                ..Default::default()
380            });
381        }
382        if let Some(id) = project_id {
383            filter.project = Some(NullableProjectFilter {
384                id: Some(IdComparator {
385                    eq: Some(cynic::Id::new(id)),
386                }),
387            });
388        }
389        if created_after.is_some() || created_before.is_some() {
390            filter.created_at = Some(DateComparator {
391                gte: created_after.map(DateTimeOrDuration),
392                lte: created_before.map(DateTimeOrDuration),
393                ..Default::default()
394            });
395        }
396        if updated_after.is_some() || updated_before.is_some() {
397            filter.updated_at = Some(DateComparator {
398                gte: updated_after.map(DateTimeOrDuration),
399                lte: updated_before.map(DateTimeOrDuration),
400                ..Default::default()
401            });
402        }
403
404        let filter_opt = (filter.priority.is_some()
405            || filter.state.is_some()
406            || filter.assignee.is_some()
407            || filter.creator.is_some()
408            || filter.team.is_some()
409            || filter.project.is_some()
410            || filter.created_at.is_some()
411            || filter.updated_at.is_some())
412        .then_some(filter);
413        let page_size = Some(first.unwrap_or(50).clamp(1, 100));
414        let q_trimmed = query.as_ref().map_or("", |s| s.trim());
415
416        if q_trimmed.is_empty() {
417            // Filters-only path: issues query
418            let op = IssuesQuery::build(IssuesArguments {
419                first: page_size,
420                after,
421                filter: filter_opt,
422            });
423
424            let resp = client.run(op).await?;
425            let data = http::extract_data(resp)?;
426
427            let issues = data.issues.nodes.into_iter().map(Into::into).collect();
428
429            Ok(models::SearchResult {
430                issues,
431                has_next_page: data.issues.page_info.has_next_page,
432                end_cursor: data.issues.page_info.end_cursor,
433            })
434        } else {
435            // Full-text search path: searchIssues
436            let op = SearchIssuesQuery::build(SearchIssuesArguments {
437                term: q_trimmed.to_string(),
438                include_comments: Some(include_comments.unwrap_or(true)),
439                first: page_size,
440                after,
441                filter: filter_opt,
442            });
443            let resp = client.run(op).await?;
444            let data = http::extract_data(resp)?;
445
446            let issues = data
447                .search_issues
448                .nodes
449                .into_iter()
450                .map(Into::into)
451                .collect();
452
453            Ok(models::SearchResult {
454                issues,
455                has_next_page: data.search_issues.page_info.has_next_page,
456                end_cursor: data.search_issues.page_info.end_cursor,
457            })
458        }
459    }
460
461    /// Read a single Linear issue
462    pub async fn read_issue(&self, issue: String) -> Result<models::IssueDetails> {
463        let client = self.client()?;
464        let resolved = Self::resolve_issue_id(&issue);
465
466        let issue_data = match resolved {
467            IssueIdentifier::Id(id) => {
468                let op = IssueByIdQuery::build(IssueByIdArguments { id });
469                let resp = client.run(op).await?;
470                let data = http::extract_data(resp)?;
471                data.issue
472                    .ok_or_else(|| anyhow::anyhow!("not found: Issue not found"))?
473            }
474            IssueIdentifier::Identifier(ident) => {
475                // Use server-side filtering by team.key + number
476                let (team_key, number) = parse_identifier(&ident)
477                    .ok_or_else(|| anyhow::anyhow!("not found: Issue {ident} not found"))?;
478                let filter = issue_filter_for_team_number(team_key, number);
479                let op = IssuesQuery::build(IssuesArguments {
480                    first: Some(1),
481                    after: None,
482                    filter: Some(filter),
483                });
484                let resp = client.run(op).await?;
485                let data = http::extract_data(resp)?;
486                data.issues
487                    .nodes
488                    .into_iter()
489                    .next()
490                    .ok_or_else(|| anyhow::anyhow!("not found: Issue {ident} not found"))?
491            }
492        };
493
494        let description = issue_data.description.clone();
495        let estimate = issue_data.estimate;
496        let started_at = issue_data.started_at.as_ref().map(|d| d.0.clone());
497        let completed_at = issue_data.completed_at.as_ref().map(|d| d.0.clone());
498        let canceled_at = issue_data.canceled_at.as_ref().map(|d| d.0.clone());
499        let parent = issue_data.parent.as_ref().map(|p| models::ParentIssueRef {
500            id: p.id.inner().to_string(),
501            identifier: p.identifier.clone(),
502        });
503
504        let summary: models::IssueSummary = issue_data.into();
505
506        Ok(models::IssueDetails {
507            issue: summary,
508            description,
509            estimate,
510            parent,
511            started_at,
512            completed_at,
513            canceled_at,
514        })
515    }
516
517    /// Create a new Linear issue
518    #[expect(clippy::too_many_arguments)]
519    pub async fn create_issue(
520        &self,
521        team_id: String,
522        title: String,
523        description: Option<String>,
524        priority: Option<i32>,
525        assignee_id: Option<String>,
526        project_id: Option<String>,
527        state_id: Option<String>,
528        parent_id: Option<String>,
529        label_ids: Vec<String>,
530    ) -> Result<models::CreateIssueResult> {
531        let client = self.client()?;
532
533        // Convert empty Vec to None for the API
534        let label_ids_opt = if label_ids.is_empty() {
535            None
536        } else {
537            Some(label_ids)
538        };
539
540        let input = IssueCreateInput {
541            team_id,
542            title: Some(title),
543            description,
544            priority,
545            assignee_id,
546            project_id,
547            state_id,
548            parent_id,
549            label_ids: label_ids_opt,
550        };
551
552        let op = IssueCreateMutation::build(IssueCreateArguments { input });
553        let resp = client.run(op).await?;
554        let data = http::extract_data(resp)?;
555
556        let payload = data.issue_create;
557        let issue: Option<models::IssueSummary> = payload.issue.map(Into::into);
558
559        Ok(models::CreateIssueResult {
560            success: payload.success,
561            issue,
562        })
563    }
564
565    /// Update an existing Linear issue
566    #[expect(clippy::too_many_arguments)]
567    pub async fn update_issue(
568        &self,
569        issue: String,
570        title: Option<String>,
571        description: Option<String>,
572        priority: Option<i32>,
573        assignee_id: Option<String>,
574        state_id: Option<String>,
575        project_id: Option<String>,
576        parent_id: Option<String>,
577        label_ids: Option<Vec<String>>,
578        added_label_ids: Option<Vec<String>>,
579        removed_label_ids: Option<Vec<String>>,
580        due_date: Option<String>,
581    ) -> Result<models::IssueResult> {
582        let client = self.client()?;
583        let id = self.resolve_to_issue_id(&client, &issue).await?;
584
585        let input = IssueUpdateInput {
586            title,
587            description,
588            priority,
589            assignee_id,
590            state_id,
591            project_id,
592            parent_id,
593            label_ids,
594            added_label_ids,
595            removed_label_ids,
596            due_date: due_date.map(linear_queries::scalars::TimelessDate),
597        };
598
599        let op = IssueUpdateMutation::build(IssueUpdateArguments { id, input });
600        let resp = client.run(op).await?;
601        let data = http::extract_data(resp)?;
602
603        let payload = data.issue_update;
604        if !payload.success {
605            anyhow::bail!("Update failed: Linear returned success=false");
606        }
607        let issue = payload
608            .issue
609            .ok_or_else(|| anyhow::anyhow!("No issue returned from update"))?;
610
611        Ok(models::IssueResult {
612            issue: issue.into(),
613        })
614    }
615
616    /// Add a comment to a Linear issue
617    pub async fn add_comment(
618        &self,
619        issue: String,
620        body: String,
621        parent_id: Option<String>,
622    ) -> Result<models::CommentResult> {
623        let client = self.client()?;
624        let issue_id = self.resolve_to_issue_id(&client, &issue).await?;
625
626        let input = CommentCreateInput {
627            issue_id,
628            body: Some(body),
629            parent_id,
630        };
631
632        let op = CommentCreateMutation::build(CommentCreateArguments { input });
633        let resp = client.run(op).await?;
634        let data = http::extract_data(resp)?;
635
636        let payload = data.comment_create;
637        let (comment_id, body, created_at) = match payload.comment {
638            Some(c) => (
639                Some(c.id.inner().to_string()),
640                Some(c.body),
641                Some(c.created_at.0),
642            ),
643            None => (None, None, None),
644        };
645
646        Ok(models::CommentResult {
647            success: payload.success,
648            comment_id,
649            body,
650            created_at,
651        })
652    }
653
654    /// Archive a Linear issue
655    pub async fn archive_issue(&self, issue: String) -> Result<models::ArchiveIssueResult> {
656        let client = self.client()?;
657        let id = self.resolve_to_issue_id(&client, &issue).await?;
658        let op = IssueArchiveMutation::build(IssueArchiveArguments { id });
659        let resp = client.run(op).await?;
660        let data = http::extract_data(resp)?;
661        Ok(models::ArchiveIssueResult {
662            success: data.issue_archive.success,
663        })
664    }
665
666    /// Get metadata (users, teams, projects, workflow states, or labels)
667    pub async fn get_metadata(
668        &self,
669        kind: models::MetadataKind,
670        search: Option<String>,
671        team_id: Option<String>,
672        first: Option<i32>,
673        after: Option<String>,
674    ) -> Result<models::GetMetadataResult> {
675        let client = self.client()?;
676        let first = first.or(Some(50));
677
678        match kind {
679            models::MetadataKind::Users => {
680                let filter = search.map(|s| linear_queries::UserFilter {
681                    display_name: Some(StringComparator {
682                        contains_ignore_case: Some(s),
683                        ..Default::default()
684                    }),
685                });
686                let op = linear_queries::UsersQuery::build(linear_queries::UsersArguments {
687                    first,
688                    after,
689                    filter,
690                });
691                let resp = client.run(op).await?;
692                let data = http::extract_data(resp)?;
693                let items = data
694                    .users
695                    .nodes
696                    .into_iter()
697                    .map(|u| {
698                        let name = if u.display_name.is_empty() {
699                            u.name
700                        } else {
701                            u.display_name
702                        };
703                        models::MetadataItem {
704                            id: u.id.inner().to_string(),
705                            name,
706                            email: Some(u.email),
707                            key: None,
708                            state_type: None,
709                            team_id: None,
710                        }
711                    })
712                    .collect();
713                Ok(models::GetMetadataResult {
714                    kind: models::MetadataKind::Users,
715                    items,
716                    has_next_page: data.users.page_info.has_next_page,
717                    end_cursor: data.users.page_info.end_cursor,
718                })
719            }
720            models::MetadataKind::Teams => {
721                let filter = search.map(|s| linear_queries::TeamFilter {
722                    key: Some(StringComparator {
723                        contains_ignore_case: Some(s),
724                        ..Default::default()
725                    }),
726                    ..Default::default()
727                });
728                let op = linear_queries::TeamsQuery::build(linear_queries::TeamsArguments {
729                    first,
730                    after,
731                    filter,
732                });
733                let resp = client.run(op).await?;
734                let data = http::extract_data(resp)?;
735                let items = data
736                    .teams
737                    .nodes
738                    .into_iter()
739                    .map(|t| models::MetadataItem {
740                        id: t.id.inner().to_string(),
741                        name: t.name,
742                        key: Some(t.key),
743                        email: None,
744                        state_type: None,
745                        team_id: None,
746                    })
747                    .collect();
748                Ok(models::GetMetadataResult {
749                    kind: models::MetadataKind::Teams,
750                    items,
751                    has_next_page: data.teams.page_info.has_next_page,
752                    end_cursor: data.teams.page_info.end_cursor,
753                })
754            }
755            models::MetadataKind::Projects => {
756                let filter = search.map(|s| linear_queries::ProjectFilter {
757                    name: Some(StringComparator {
758                        contains_ignore_case: Some(s),
759                        ..Default::default()
760                    }),
761                });
762                let op = linear_queries::ProjectsQuery::build(linear_queries::ProjectsArguments {
763                    first,
764                    after,
765                    filter,
766                });
767                let resp = client.run(op).await?;
768                let data = http::extract_data(resp)?;
769                let items = data
770                    .projects
771                    .nodes
772                    .into_iter()
773                    .map(|p| models::MetadataItem {
774                        id: p.id.inner().to_string(),
775                        name: p.name,
776                        key: None,
777                        email: None,
778                        state_type: None,
779                        team_id: None,
780                    })
781                    .collect();
782                Ok(models::GetMetadataResult {
783                    kind: models::MetadataKind::Projects,
784                    items,
785                    has_next_page: data.projects.page_info.has_next_page,
786                    end_cursor: data.projects.page_info.end_cursor,
787                })
788            }
789            models::MetadataKind::WorkflowStates => {
790                let filter_opt = if let Some(s) = search {
791                    let mut filter = linear_queries::WorkflowStateFilter {
792                        name: Some(StringComparator {
793                            contains_ignore_case: Some(s),
794                            ..Default::default()
795                        }),
796                        ..Default::default()
797                    };
798                    if let Some(tid) = team_id {
799                        filter.team = Some(linear_queries::TeamFilter {
800                            id: Some(linear_queries::IdComparator {
801                                eq: Some(cynic::Id::new(tid)),
802                            }),
803                            ..Default::default()
804                        });
805                    }
806                    Some(filter)
807                } else {
808                    team_id.map(|tid| linear_queries::WorkflowStateFilter {
809                        team: Some(linear_queries::TeamFilter {
810                            id: Some(linear_queries::IdComparator {
811                                eq: Some(cynic::Id::new(tid)),
812                            }),
813                            ..Default::default()
814                        }),
815                        ..Default::default()
816                    })
817                };
818                let op = linear_queries::WorkflowStatesQuery::build(
819                    linear_queries::WorkflowStatesArguments {
820                        first,
821                        after,
822                        filter: filter_opt,
823                    },
824                );
825                let resp = client.run(op).await?;
826                let data = http::extract_data(resp)?;
827                let items = data
828                    .workflow_states
829                    .nodes
830                    .into_iter()
831                    .map(|s| models::MetadataItem {
832                        id: s.id.inner().to_string(),
833                        name: s.name,
834                        state_type: Some(s.state_type),
835                        key: None,
836                        email: None,
837                        team_id: None,
838                    })
839                    .collect();
840                Ok(models::GetMetadataResult {
841                    kind: models::MetadataKind::WorkflowStates,
842                    items,
843                    has_next_page: data.workflow_states.page_info.has_next_page,
844                    end_cursor: data.workflow_states.page_info.end_cursor,
845                })
846            }
847            models::MetadataKind::Labels => {
848                let filter_opt = if let Some(s) = search {
849                    let mut filter = linear_queries::IssueLabelFilter {
850                        name: Some(StringComparator {
851                            contains_ignore_case: Some(s),
852                            ..Default::default()
853                        }),
854                        ..Default::default()
855                    };
856                    if let Some(tid) = team_id {
857                        filter.team = Some(linear_queries::NullableTeamFilter {
858                            id: Some(linear_queries::IdComparator {
859                                eq: Some(cynic::Id::new(tid)),
860                            }),
861                            ..Default::default()
862                        });
863                    }
864                    Some(filter)
865                } else {
866                    team_id.map(|tid| linear_queries::IssueLabelFilter {
867                        team: Some(linear_queries::NullableTeamFilter {
868                            id: Some(linear_queries::IdComparator {
869                                eq: Some(cynic::Id::new(tid)),
870                            }),
871                            ..Default::default()
872                        }),
873                        ..Default::default()
874                    })
875                };
876                let op =
877                    linear_queries::IssueLabelsQuery::build(linear_queries::IssueLabelsArguments {
878                        first,
879                        after,
880                        filter: filter_opt,
881                    });
882                let resp = client.run(op).await?;
883                let data = http::extract_data(resp)?;
884                let items = data
885                    .issue_labels
886                    .nodes
887                    .into_iter()
888                    .map(|l| models::MetadataItem {
889                        id: l.id.inner().to_string(),
890                        name: l.name,
891                        team_id: l.team.map(|t| t.id.inner().to_string()),
892                        key: None,
893                        email: None,
894                        state_type: None,
895                    })
896                    .collect();
897                Ok(models::GetMetadataResult {
898                    kind: models::MetadataKind::Labels,
899                    items,
900                    has_next_page: data.issue_labels.page_info.has_next_page,
901                    end_cursor: data.issue_labels.page_info.end_cursor,
902                })
903            }
904        }
905    }
906
907    /// Set or remove a relation between two issues
908    pub async fn set_relation(
909        &self,
910        issue: String,
911        related_issue: String,
912        relation_type: Option<String>,
913    ) -> Result<models::SetRelationResult> {
914        let client = self.client()?;
915        let issue_id = self.resolve_to_issue_id(&client, &issue).await?;
916        let related_issue_id = self.resolve_to_issue_id(&client, &related_issue).await?;
917
918        if let Some(rel_type) = relation_type {
919            // Create relation
920            let relation_type = match rel_type.to_lowercase().as_str() {
921                "blocks" => IssueRelationType::Blocks,
922                "duplicate" => IssueRelationType::Duplicate,
923                "related" => IssueRelationType::Related,
924                other => anyhow::bail!(
925                    "Invalid relation type: {other}. Must be one of: blocks, duplicate, related"
926                ),
927            };
928
929            let input = IssueRelationCreateInput {
930                issue_id,
931                related_issue_id,
932                relation_type,
933            };
934
935            let op = IssueRelationCreateMutation::build(IssueRelationCreateArguments { input });
936            let resp = client.run(op).await?;
937            let data = http::extract_data(resp)?;
938
939            Ok(models::SetRelationResult {
940                success: data.issue_relation_create.success,
941                action: "created".to_string(),
942            })
943        } else {
944            // Remove relation - need to find it first
945            let op = IssueRelationsQuery::build(IssueRelationsArguments { id: issue_id });
946            let resp = client.run(op).await?;
947            let data = http::extract_data(resp)?;
948
949            let issue_with_relations = data
950                .issue
951                .ok_or_else(|| anyhow::anyhow!("not found: Issue not found"))?;
952
953            // Search in both relations and inverse_relations
954            let relation_id = issue_with_relations
955                .relations
956                .nodes
957                .iter()
958                .find(|r| r.related_issue.id.inner() == related_issue_id)
959                .map(|r| r.id.inner().to_string())
960                .or_else(|| {
961                    issue_with_relations
962                        .inverse_relations
963                        .nodes
964                        .iter()
965                        .find(|r| r.related_issue.id.inner() == related_issue_id)
966                        .map(|r| r.id.inner().to_string())
967                });
968
969            match relation_id {
970                Some(id) => {
971                    let op =
972                        IssueRelationDeleteMutation::build(IssueRelationDeleteArguments { id });
973                    let resp = client.run(op).await?;
974                    let data = http::extract_data(resp)?;
975
976                    Ok(models::SetRelationResult {
977                        success: data.issue_relation_delete.success,
978                        action: "removed".to_string(),
979                    })
980                }
981                None => {
982                    // No relation found - idempotent success
983                    Ok(models::SetRelationResult {
984                        success: true,
985                        action: "no_change".to_string(),
986                    })
987                }
988            }
989        }
990    }
991
992    /// Get comments on a Linear issue with implicit pagination
993    pub async fn get_issue_comments(&self, issue: String) -> Result<models::CommentsResult> {
994        let client = self.client()?;
995
996        // Resolve issue identifier to UUID
997        let issue_id = self.resolve_to_issue_id(&client, &issue).await?;
998
999        // Cache key includes page size for correctness
1000        let cache_key = format!("{issue_id}|{COMMENTS_PAGE_SIZE}");
1001
1002        // Sweep expired entries
1003        self.comments_cache.sweep_expired();
1004
1005        // Get or create cache entry
1006        let query_lock = self.comments_cache.get_or_create(&cache_key);
1007
1008        // Check if we need to fetch
1009        let needs_fetch = {
1010            let state = query_lock.lock_state();
1011            state.is_empty() || state.is_expired()
1012        };
1013
1014        // Store the issue identifier for display
1015        let issue_identifier: String;
1016
1017        if needs_fetch {
1018            // Fetch all comments from Linear API
1019            let (identifier, all_comments) = Self::fetch_all_comments(&client, &issue_id).await?;
1020            issue_identifier = identifier.clone();
1021
1022            // Reset cache with fresh data (stores canonical identifier)
1023            let mut state = query_lock.lock_state();
1024            if state.is_empty() || state.is_expired() {
1025                state.reset(all_comments, identifier, COMMENTS_PAGE_SIZE);
1026            }
1027        } else {
1028            // Get canonical identifier from cache
1029            let state = query_lock.lock_state();
1030            issue_identifier = state.meta.clone();
1031        }
1032
1033        // Paginate from cache
1034        let (page_comments, total, shown, has_more) = {
1035            let mut state = query_lock.lock_state();
1036            let (page, has_more) =
1037                paginate_slice(&state.results, state.next_offset, state.page_size);
1038            let total = state.results.len();
1039            state.next_offset += page.len();
1040            let shown = state.next_offset;
1041            (page, total, shown, has_more)
1042        };
1043
1044        // If exhausted, remove cache entry so next call restarts
1045        if !has_more {
1046            self.comments_cache.remove_if_same(&cache_key, &query_lock);
1047        }
1048
1049        Ok(models::CommentsResult {
1050            issue_identifier,
1051            comments: page_comments,
1052            shown_comments: shown,
1053            total_comments: total,
1054            has_more,
1055        })
1056    }
1057
1058    async fn fetch_all_comments(
1059        client: &LinearClient,
1060        issue_id: &str,
1061    ) -> Result<(String, Vec<models::CommentSummary>)> {
1062        let mut cursor: Option<String> = None;
1063        let mut all_comments = Vec::new();
1064        let mut identifier: Option<String> = None;
1065
1066        for page in 0..ISSUE_COMMENTS_MAX_PAGES {
1067            let args = IssueCommentsArguments {
1068                id: issue_id.to_string(),
1069                first: Some(ISSUE_COMMENTS_FETCH_PAGE_SIZE),
1070                after: cursor.clone(),
1071            };
1072            let op = IssueCommentsQuery::build(args);
1073            let resp = client.run(op).await?;
1074            let data = http::extract_data(resp)?;
1075
1076            let issue = data
1077                .issue
1078                .ok_or_else(|| anyhow::anyhow!("Issue not found: {issue_id}"))?;
1079
1080            if identifier.is_none() {
1081                identifier = Some(issue.identifier.clone());
1082            }
1083
1084            all_comments.extend(
1085                issue
1086                    .comments
1087                    .nodes
1088                    .into_iter()
1089                    .map(|c| models::CommentSummary {
1090                        id: c.id.inner().to_string(),
1091                        body: c.body,
1092                        url: c.url,
1093                        created_at: c.created_at.0,
1094                        updated_at: c.updated_at.0,
1095                        parent_id: c.parent_id,
1096                        author_name: c.user.as_ref().map(|u| u.name.clone()),
1097                        author_email: c.user.as_ref().map(|u| u.email.clone()),
1098                    }),
1099            );
1100
1101            if !issue.comments.page_info.has_next_page {
1102                all_comments.sort_by(|a, b| a.created_at.cmp(&b.created_at));
1103                return Ok((identifier.unwrap_or_default(), all_comments));
1104            }
1105
1106            cursor.clone_from(&issue.comments.page_info.end_cursor);
1107            if cursor.is_none() {
1108                return Err(anyhow::anyhow!(
1109                    "Issue comments pagination for {issue_id} reported has_next_page=true without end_cursor"
1110                ));
1111            }
1112
1113            if page + 1 == ISSUE_COMMENTS_MAX_PAGES {
1114                return Err(anyhow::anyhow!(
1115                    "Issue comments pagination for {issue_id} exceeded {ISSUE_COMMENTS_MAX_PAGES} pages"
1116                ));
1117            }
1118        }
1119
1120        unreachable!("issue comments pagination loop must return or error")
1121    }
1122}
1123
1124// Removed universal-tool-core MCP server; use ToolRegistry in tools.rs
1125
1126#[cfg(test)]
1127mod tests {
1128    use super::parse_identifier;
1129
1130    #[test]
1131    fn parse_plain_uppercase() {
1132        assert_eq!(parse_identifier("ENG-245"), Some(("ENG".into(), 245)));
1133    }
1134
1135    #[test]
1136    fn parse_lowercase_normalizes() {
1137        assert_eq!(parse_identifier("eng-245"), Some(("ENG".into(), 245)));
1138    }
1139
1140    #[test]
1141    fn parse_from_url() {
1142        assert_eq!(
1143            parse_identifier("https://linear.app/foo/issue/eng-245/slug"),
1144            Some(("ENG".into(), 245))
1145        );
1146    }
1147
1148    #[test]
1149    fn parse_invalid_returns_none() {
1150        assert_eq!(parse_identifier("invalid"), None);
1151        assert_eq!(parse_identifier("ENG-"), None);
1152        assert_eq!(parse_identifier("ENG"), None);
1153        assert_eq!(parse_identifier("123-456"), None);
1154    }
1155}