task-mcp 0.5.0

MCP server for task runner integration — Agent-safe harness for defined tasks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use rmcp::{
    ErrorData as McpError, ServerHandler, ServiceExt,
    handler::server::{tool::ToolRouter, wrapper::Parameters},
    model::{
        CallToolRequestParams, CallToolResult, Content, Implementation, ListToolsResult,
        PaginatedRequestParams, ProtocolVersion, ServerCapabilities, ServerInfo,
    },
    service::{RequestContext, RoleServer},
    tool, tool_router,
    transport::stdio,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

use crate::config::Config;
use crate::just;
use crate::template;

// =============================================================================
// Group filter matcher
// =============================================================================

/// Glob-style matcher for the `list.filter` field.
///
/// Supported wildcards: `*` (zero or more chars), `?` (exactly one char).
/// Patterns without wildcards fall back to exact string equality so users can
/// keep specifying a plain group name like `profile`.
enum GroupMatcher {
    Exact(String),
    Glob(regex::Regex),
}

impl GroupMatcher {
    fn new(pattern: &str) -> Self {
        if !pattern.contains('*') && !pattern.contains('?') {
            return Self::Exact(pattern.to_string());
        }
        let mut re = String::with_capacity(pattern.len() + 2);
        re.push('^');
        let mut literal = String::new();
        let flush = |re: &mut String, literal: &mut String| {
            if !literal.is_empty() {
                re.push_str(&regex::escape(literal));
                literal.clear();
            }
        };
        for c in pattern.chars() {
            match c {
                '*' => {
                    flush(&mut re, &mut literal);
                    re.push_str(".*");
                }
                '?' => {
                    flush(&mut re, &mut literal);
                    re.push('.');
                }
                c => literal.push(c),
            }
        }
        flush(&mut re, &mut literal);
        re.push('$');
        match regex::Regex::new(&re) {
            Ok(r) => Self::Glob(r),
            // Fallback: treat an unusable pattern as exact match on the raw input.
            Err(_) => Self::Exact(pattern.to_string()),
        }
    }

    fn is_match(&self, group: &str) -> bool {
        match self {
            Self::Exact(s) => s == group,
            Self::Glob(r) => r.is_match(group),
        }
    }
}

// =============================================================================
// Public entry point
// =============================================================================

pub async fn run() -> anyhow::Result<()> {
    let config = Config::load();
    let server_cwd = std::env::current_dir()?;
    let server = TaskMcpServer::new(config, server_cwd);
    let service = server.serve(stdio()).await?;
    service.waiting().await?;
    Ok(())
}

// =============================================================================
// MCP Server
// =============================================================================

#[derive(Clone)]
pub struct TaskMcpServer {
    tool_router: ToolRouter<Self>,
    config: Config,
    log_store: Arc<just::TaskLogStore>,
    /// Runtime working directory set by `session_start`.
    workdir: Arc<RwLock<Option<PathBuf>>>,
    /// CWD at server startup (used as default when session_start omits workdir).
    server_cwd: PathBuf,
}

/// Outcome of a lazy auto-session-start attempt.
///
/// Distinguishes the reasons the server may decline to auto-start so that
/// callers can produce actionable error messages and — crucially — recover
/// when a concurrent task has already initialized the session.
#[derive(Debug)]
pub(crate) enum AutoStartOutcome {
    /// Session was newly initialized by this call.
    Started(SessionStartResponse, PathBuf),
    /// Session had already been initialized (by a concurrent task) when we
    /// acquired the write lock. The existing workdir is returned so the
    /// caller can proceed without a spurious error.
    AlreadyStarted(PathBuf),
    /// `server_cwd` is not a ProjectRoot (no `.git`/`justfile` marker).
    NotProjectRoot,
    /// `server_cwd` could not be canonicalized.
    CanonicalizeFailed(std::io::Error),
    /// `server_cwd` is not in `allowed_dirs`.
    NotAllowed(PathBuf),
}

impl TaskMcpServer {
    pub fn new(config: Config, server_cwd: PathBuf) -> Self {
        Self {
            tool_router: Self::tool_router(),
            config,
            log_store: Arc::new(just::TaskLogStore::new(10)),
            workdir: Arc::new(RwLock::new(None)),
            server_cwd,
        }
    }

    /// Try to auto-start a session using `server_cwd` as the workdir.
    ///
    /// See [`AutoStartOutcome`] for the return variants.
    pub(crate) async fn try_auto_session_start(&self) -> AutoStartOutcome {
        // Check if server_cwd is a ProjectRoot (.git or justfile must exist)
        let has_git = tokio::fs::try_exists(self.server_cwd.join(".git"))
            .await
            .unwrap_or(false);
        let has_justfile = tokio::fs::try_exists(self.server_cwd.join("justfile"))
            .await
            .unwrap_or(false);
        if !has_git && !has_justfile {
            return AutoStartOutcome::NotProjectRoot;
        }

        // Canonicalize server_cwd
        let canonical = match tokio::fs::canonicalize(&self.server_cwd).await {
            Ok(p) => p,
            Err(e) => return AutoStartOutcome::CanonicalizeFailed(e),
        };

        // Check allowed_dirs
        if !self.config.is_workdir_allowed(&canonical) {
            return AutoStartOutcome::NotAllowed(canonical);
        }

        // Double-checked locking: acquire write lock, then re-check None.
        // If another task initialized the session between our fast-path read
        // and this write lock, return AlreadyStarted so the caller can reuse
        // the existing workdir instead of reporting a spurious error.
        let mut guard = self.workdir.write().await;
        if let Some(ref existing) = *guard {
            return AutoStartOutcome::AlreadyStarted(existing.clone());
        }
        *guard = Some(canonical.clone());
        drop(guard);

        let justfile =
            resolve_justfile_with_workdir(self.config.justfile_path.as_deref(), &canonical);

        AutoStartOutcome::Started(
            SessionStartResponse {
                workdir: canonical.to_string_lossy().into_owned(),
                justfile: justfile.to_string_lossy().into_owned(),
                mode: mode_label(&self.config),
            },
            canonical,
        )
    }

    /// Return the current session workdir (with optional auto-start) and the auto-start response.
    ///
    /// - If session is already started, returns `(workdir, None)`.
    /// - If not started and `server_cwd` is a ProjectRoot, auto-starts and returns `(workdir, Some(response))`.
    /// - If a concurrent task initialized the session while we were in the slow path, returns `(workdir, None)`.
    /// - Otherwise returns a specific error describing which precondition failed.
    pub(crate) async fn workdir_or_auto(
        &self,
    ) -> Result<(PathBuf, Option<SessionStartResponse>), McpError> {
        // Fast path: session already started
        {
            let guard = self.workdir.read().await;
            if let Some(ref wd) = *guard {
                return Ok((wd.clone(), None));
            }
        }

        // Slow path: try auto-start
        match self.try_auto_session_start().await {
            AutoStartOutcome::Started(resp, wd) => Ok((wd, Some(resp))),
            AutoStartOutcome::AlreadyStarted(wd) => Ok((wd, None)),
            AutoStartOutcome::NotProjectRoot => Err(McpError::internal_error(
                format!(
                    "session not started. server startup CWD {:?} is not a ProjectRoot (no .git or justfile). Call session_start with an explicit workdir.",
                    self.server_cwd
                ),
                None,
            )),
            AutoStartOutcome::CanonicalizeFailed(e) => Err(McpError::internal_error(
                format!(
                    "session not started. failed to canonicalize server startup CWD {:?}: {e}. Call session_start with an explicit workdir.",
                    self.server_cwd
                ),
                None,
            )),
            AutoStartOutcome::NotAllowed(path) => Err(McpError::internal_error(
                format!(
                    "session not started. server startup CWD {:?} is not in allowed_dirs. Call session_start with an allowed workdir.",
                    path
                ),
                None,
            )),
        }
    }
}

// =============================================================================
// ServerHandler impl
// =============================================================================

impl ServerHandler for TaskMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::V_2025_03_26,
            capabilities: ServerCapabilities::builder().enable_tools().build(),
            server_info: Implementation {
                name: "task-mcp".to_string(),
                title: Some("Task MCP — Agent-safe Task Runner".to_string()),
                description: Some(
                    "Execute predefined justfile tasks safely. \
                     6 tools: session_start, info, init, list, run, logs."
                        .to_string(),
                ),
                version: env!("CARGO_PKG_VERSION").to_string(),
                icons: None,
                website_url: None,
            },
            instructions: Some(
                "Agent-safe task runner backed by just.\n\
                 \n\
                 - `session_start`: Set working directory explicitly. Optional when the \
                 server was launched inside a ProjectRoot (a directory containing `.git` \
                 or `justfile`) — in that case the first `init`/`list`/`run` call auto-starts \
                 the session using the server's startup CWD. Call `session_start` explicitly \
                 only when you need a different workdir (e.g. a subdirectory in a monorepo).\n\
                 - `info`: Show current session state (workdir, mode, etc).\n\
                 - `init`: Generate a justfile in the working directory.\n\
                 - `list`: Show available tasks filtered by the allow-agent marker.\n\
                 - `run`: Execute a named task. Supports `content` arguments for raw text (newlines allowed).\n\
                 - `logs`: Retrieve execution logs of recent runs.\n\
                 \n\
                 When a call auto-starts the session, the response includes an \
                 `auto_session_start` field with the chosen workdir, justfile, and mode. \
                 Subsequent calls in the same session do not include this field.\n\
                 \n\
                 Allow-agent is a security boundary: in the default `agent-only` mode, \
                 recipes without the `[group('allow-agent')]` attribute (or the legacy \
                 `# [allow-agent]` doc comment) are NEVER exposed via MCP. The mode is \
                 controlled by the `TASK_MCP_MODE` environment variable, set OUTSIDE \
                 the MCP. Reading the justfile directly bypasses this guard, but is \
                 not the canonical path."
                    .to_string(),
            ),
        }
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, McpError> {
        Ok(ListToolsResult {
            tools: self.tool_router.list_all(),
            next_cursor: None,
            meta: None,
        })
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResult, McpError> {
        let tool_ctx = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
        self.tool_router.call(tool_ctx).await
    }
}

// =============================================================================
// Request / Response types
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
struct SessionStartRequest {
    /// Working directory path. If omitted or empty, defaults to the server's startup CWD.
    pub workdir: Option<String>,
}

/// Response payload describing a session's working directory, resolved justfile,
/// and active task mode. Returned by `session_start`, and also embedded as
/// `auto_session_start` in other tools' responses when the session was
/// automatically started by that call.
#[derive(Debug, Clone, Serialize)]
pub(crate) struct SessionStartResponse {
    /// Canonicalized absolute path of the working directory.
    pub workdir: String,
    /// Resolved path to the justfile used in this session.
    pub justfile: String,
    /// Active task mode: "agent-only" or "all".
    pub mode: String,
}

#[derive(Debug, Clone, Serialize)]
struct InfoResponse {
    /// Whether session_start has been called.
    pub session_started: bool,
    /// Current working directory (None if session_start not yet called).
    pub workdir: Option<String>,
    /// Resolved justfile path (None if session_start not yet called).
    pub justfile: Option<String>,
    /// Active task mode: "agent-only" or "all".
    pub mode: String,
    /// CWD at server startup.
    pub server_cwd: String,
    /// Whether global justfile merging is enabled.
    pub load_global: bool,
    /// Resolved global justfile path (None when load_global=false or global file not found).
    pub global_justfile: Option<String>,
    /// Links to documentation.
    pub docs: InfoDocs,
}

#[derive(Debug, Clone, Serialize)]
struct InfoDocs {
    /// Execution model guide (how task-mcp processes recipe arguments).
    pub execution_model: &'static str,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
struct InitRequest {
    /// Project type: "rust" (default) or "vite-react".
    pub project_type: Option<String>,
    /// Path to a custom template file (must be under session workdir). Overrides TASK_MCP_INIT_TEMPLATE_FILE env.
    pub template_file: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
struct InitResponse {
    /// Path to the generated justfile.
    pub justfile: String,
    /// Project type used for template selection.
    pub project_type: String,
    /// Whether a custom template file was used.
    pub custom_template: bool,
    /// Present only when this call triggered an automatic session_start because
    /// no session was active and the server's startup CWD is a ProjectRoot
    /// (contains `.git` or `justfile`). Contains the resolved workdir, justfile
    /// path, and mode. Absent on subsequent calls within the same session.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auto_session_start: Option<SessionStartResponse>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
struct ListRequest {
    /// Filter recipes by group name. Supports glob wildcards: `*` matches any
    /// sequence of characters and `?` matches a single character (e.g.
    /// `prof*`, `ci-?`, `*-release`). A pattern without wildcards is treated as
    /// an exact match. If omitted, all agent-safe recipes are returned.
    pub filter: Option<String>,
    /// Justfile path override. Defaults to `justfile` in the current directory.
    pub justfile: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
struct RunRequest {
    /// Name of the recipe to execute (must appear in `list` output).
    pub task_name: String,
    /// Named arguments to pass to the recipe.  Keys must match recipe parameter names.
    pub args: Option<HashMap<String, String>>,
    /// Content arguments passed as environment variables to the recipe.
    /// Keys become `TASK_MCP_CONTENT_{KEY}` (uppercased). Values can contain
    /// any UTF-8 text including newlines — no escaping needed.
    pub content: Option<HashMap<String, String>>,
    /// Execution timeout in seconds (default: 60).
    pub timeout_secs: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
struct LogsRequest {
    /// Retrieve the full output of a specific execution by its UUID.
    /// If omitted, a summary of the 10 most recent executions is returned.
    pub task_id: Option<String>,
    /// When a `task_id` is provided, restrict the stdout to the last N lines.
    /// Ignored when `task_id` is absent.
    pub tail: Option<usize>,
}

// =============================================================================
// Helpers
// =============================================================================

/// Resolve the justfile path taking a session workdir into account.
///
/// If `override_path` is provided it is used as-is (absolute or relative to CWD).
/// Otherwise `{workdir}/justfile` is returned.
fn resolve_justfile_with_workdir(
    override_path: Option<&str>,
    workdir: &std::path::Path,
) -> PathBuf {
    match override_path {
        Some(p) => PathBuf::from(p),
        None => workdir.join("justfile"),
    }
}

/// Return the last `n` lines of `text`.  If `n` exceeds the line count, the
/// full text is returned unchanged.
fn tail_lines(text: &str, n: usize) -> String {
    let lines: Vec<&str> = text.lines().collect();
    if n >= lines.len() {
        return text.to_string();
    }
    lines[lines.len() - n..].join("\n")
}

fn mode_label(config: &Config) -> String {
    use crate::config::TaskMode;
    match config.mode {
        TaskMode::AgentOnly => "agent-only".to_string(),
        TaskMode::All => "all".to_string(),
    }
}

// =============================================================================
// Tool implementations
// =============================================================================

#[tool_router]
impl TaskMcpServer {
    #[tool(
        name = "session_start",
        description = "Set the working directory for this session explicitly. Optional when the server was launched inside a ProjectRoot (directory containing `.git` or `justfile`): the first `init`/`list`/`run` call will auto-start the session using the server's startup CWD. Call this tool to override that default, e.g. when working in a monorepo subdirectory. Subsequent `run` and `list` (without justfile param) use the configured directory.",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn session_start(
        &self,
        Parameters(req): Parameters<SessionStartRequest>,
    ) -> Result<CallToolResult, McpError> {
        // Determine the target directory: use provided path or fall back to server CWD.
        let raw_path = match req.workdir.as_deref() {
            Some(s) if !s.trim().is_empty() => PathBuf::from(s),
            _ => self.server_cwd.clone(),
        };

        // Canonicalize (resolves symlinks, checks existence).
        let canonical = tokio::fs::canonicalize(&raw_path).await.map_err(|e| {
            McpError::invalid_params(
                format!(
                    "workdir {:?} does not exist or is not accessible: {e}",
                    raw_path
                ),
                None,
            )
        })?;

        // Verify against allowed_dirs.
        if !self.config.is_workdir_allowed(&canonical) {
            return Err(McpError::invalid_params(
                format!(
                    "workdir {:?} is not in the allowed directories list",
                    canonical
                ),
                None,
            ));
        }

        // Persist in session state.
        *self.workdir.write().await = Some(canonical.clone());

        let justfile =
            resolve_justfile_with_workdir(self.config.justfile_path.as_deref(), &canonical);

        let response = SessionStartResponse {
            workdir: canonical.to_string_lossy().into_owned(),
            justfile: justfile.to_string_lossy().into_owned(),
            mode: mode_label(&self.config),
        };

        let output = serde_json::to_string_pretty(&response)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult {
            content: vec![Content::text(output)],
            structured_content: None,
            is_error: Some(false),
            meta: None,
        })
    }

    #[tool(
        name = "init",
        description = "Generate a justfile with agent-safe recipes in the session working directory. The session is auto-started if the server was launched inside a ProjectRoot; otherwise call `session_start` first. Supports project types: rust (default), vite-react. Custom template files can also be specified. Fails if justfile already exists — delete it first to regenerate.",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = false,
            open_world_hint = false
        )
    )]
    async fn init(
        &self,
        Parameters(req): Parameters<InitRequest>,
    ) -> Result<CallToolResult, McpError> {
        let (workdir, auto) = self.workdir_or_auto().await?;

        // Parse project type
        let project_type = match req.project_type.as_deref() {
            Some(s) => s
                .parse::<template::ProjectType>()
                .map_err(|e| McpError::invalid_params(e, None))?,
            None => template::ProjectType::default(),
        };

        let justfile_path = workdir.join("justfile");

        // Reject if justfile already exists
        if justfile_path.exists() {
            return Err(McpError::invalid_params(
                format!(
                    "justfile already exists at {}. Delete it first if you want to regenerate.",
                    justfile_path.display()
                ),
                None,
            ));
        }

        // Validate template_file is under workdir (prevent path traversal)
        if let Some(ref tf) = req.template_file {
            let template_path = std::fs::canonicalize(tf).map_err(|e| {
                McpError::invalid_params(
                    format!("template_file {tf:?} is not accessible: {e}"),
                    None,
                )
            })?;
            if !template_path.starts_with(&workdir) {
                return Err(McpError::invalid_params(
                    format!(
                        "template_file must be under session workdir ({}). Got: {}",
                        workdir.display(),
                        template_path.display()
                    ),
                    None,
                ));
            }
        }

        // Resolve template content
        let custom_template_used =
            req.template_file.is_some() || self.config.init_template_file.is_some();

        let content = template::resolve_template(
            project_type,
            req.template_file.as_deref(),
            self.config.init_template_file.as_deref(),
        )
        .await
        .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        // Write justfile
        tokio::fs::write(&justfile_path, &content)
            .await
            .map_err(|e| {
                McpError::internal_error(
                    format!(
                        "failed to write justfile at {}: {e}",
                        justfile_path.display()
                    ),
                    None,
                )
            })?;

        let response = InitResponse {
            justfile: justfile_path.to_string_lossy().into_owned(),
            project_type: project_type.to_string(),
            custom_template: custom_template_used,
            auto_session_start: auto,
        };

        let output = serde_json::to_string_pretty(&response)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult {
            content: vec![Content::text(output)],
            structured_content: None,
            is_error: Some(false),
            meta: None,
        })
    }

    #[tool(
        name = "info",
        description = "Show current session state: workdir, justfile path, mode, and server startup CWD.",
        annotations(
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn info(&self) -> Result<CallToolResult, McpError> {
        let current_workdir = self.workdir.read().await.clone();

        let (session_started, workdir_str, justfile_str) = match current_workdir {
            Some(ref wd) => {
                let justfile =
                    resolve_justfile_with_workdir(self.config.justfile_path.as_deref(), wd);
                (
                    true,
                    Some(wd.to_string_lossy().into_owned()),
                    Some(justfile.to_string_lossy().into_owned()),
                )
            }
            None => (false, None, None),
        };

        let global_justfile_str = self
            .config
            .global_justfile_path
            .as_ref()
            .map(|p| p.to_string_lossy().into_owned());

        let response = InfoResponse {
            session_started,
            workdir: workdir_str,
            justfile: justfile_str,
            mode: mode_label(&self.config),
            server_cwd: self.server_cwd.to_string_lossy().into_owned(),
            load_global: self.config.load_global,
            global_justfile: global_justfile_str,
            docs: InfoDocs {
                execution_model: "https://github.com/ynishi/task-mcp/blob/master/docs/execution-model.md",
            },
        };

        let output = serde_json::to_string_pretty(&response)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult {
            content: vec![Content::text(output)],
            structured_content: None,
            is_error: Some(false),
            meta: None,
        })
    }

    #[tool(
        name = "list",
        description = "List available tasks from justfile. Returns an object `{\"recipes\": [...]}` containing task names, descriptions, parameters, and groups. When this call triggers an automatic session_start, the response also includes an `auto_session_start` field.",
        annotations(
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn list(
        &self,
        Parameters(req): Parameters<ListRequest>,
    ) -> Result<CallToolResult, McpError> {
        let (justfile_path, workdir_opt, auto) = if req.justfile.is_some() {
            // justfile parameter specified → session_start not required
            let jp = just::resolve_justfile_path(
                req.justfile
                    .as_deref()
                    .or(self.config.justfile_path.as_deref()),
                None,
            );
            (jp, None, None)
        } else {
            // no justfile parameter → session_start is required (or auto-started)
            let (wd, auto) = self.workdir_or_auto().await?;
            let jp = just::resolve_justfile_path(self.config.justfile_path.as_deref(), Some(&wd));
            (jp, Some(wd), auto)
        };

        // SECURITY GUARD: `list_recipes` / `list_recipes_merged` apply the
        // allow-agent filter internally based on `self.config.mode`. Any recipe
        // returned here has already passed the agent-only gate (when active).
        // Do NOT reorder this with `filter` post-processing — the guard must
        // run first so that non-allowed recipes never enter the agent context.
        let recipes = if self.config.load_global {
            just::list_recipes_merged(
                &justfile_path,
                self.config.global_justfile_path.as_deref(),
                &self.config.mode,
                workdir_opt.as_deref(),
            )
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?
        } else {
            just::list_recipes(&justfile_path, &self.config.mode, workdir_opt.as_deref())
                .await
                .map_err(|e| McpError::internal_error(e.to_string(), None))?
        };

        // Functional group filter (e.g. `profile`, `issue`). Applied AFTER the
        // security guard above. The filter value `allow-agent` is not
        // meaningful in agent-only mode (every recipe already carries it).
        // Apply optional group filter with glob matching (`*`, `?`).
        let filtered: Vec<_> = match &req.filter {
            Some(pattern) => {
                let matcher = GroupMatcher::new(pattern);
                recipes
                    .into_iter()
                    .filter(|r| r.groups.iter().any(|g| matcher.is_match(g)))
                    .collect()
            }
            None => recipes,
        };

        let mut wrapped = serde_json::json!({ "recipes": filtered });
        if let Some(auto_response) = auto {
            wrapped.as_object_mut().expect("json object").insert(
                "auto_session_start".to_string(),
                serde_json::to_value(auto_response)
                    .map_err(|e| McpError::internal_error(e.to_string(), None))?,
            );
        }
        let output = serde_json::to_string_pretty(&wrapped)
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult {
            content: vec![Content::text(output)],
            structured_content: None,
            is_error: Some(false),
            meta: None,
        })
    }

    #[tool(
        name = "run",
        description = "Execute a predefined task. Only tasks visible in `list` can be run. Pass `content` for raw text arguments (newlines allowed) — delivered as env vars (`TASK_MCP_CONTENT_*`) to the recipe.",
        annotations(
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = false,
            open_world_hint = false
        )
    )]
    async fn run(
        &self,
        Parameters(req): Parameters<RunRequest>,
    ) -> Result<CallToolResult, McpError> {
        // session_start is required for run (auto-start if ProjectRoot)
        let (workdir, auto) = self.workdir_or_auto().await?;
        let justfile_path =
            just::resolve_justfile_path(self.config.justfile_path.as_deref(), Some(&workdir));
        let args = req.args.unwrap_or_default();
        let content = req.content.unwrap_or_default();
        let timeout = Duration::from_secs(req.timeout_secs.unwrap_or(60));

        let execution = if self.config.load_global {
            just::execute_recipe_merged(
                &req.task_name,
                &args,
                &content,
                &justfile_path,
                self.config.global_justfile_path.as_deref(),
                timeout,
                &self.config.mode,
                Some(&workdir),
            )
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?
        } else {
            just::execute_recipe(
                &req.task_name,
                &args,
                &content,
                &justfile_path,
                timeout,
                &self.config.mode,
                Some(&workdir),
            )
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?
        };

        // Persist to log store
        self.log_store.push(execution.clone());

        let is_error = execution.exit_code.map(|c| c != 0).unwrap_or(true);

        let output = match auto {
            Some(auto_response) => {
                let mut val = serde_json::to_value(&execution)
                    .map_err(|e| McpError::internal_error(e.to_string(), None))?;
                if let Some(obj) = val.as_object_mut() {
                    obj.insert(
                        "auto_session_start".to_string(),
                        serde_json::to_value(auto_response)
                            .map_err(|e| McpError::internal_error(e.to_string(), None))?,
                    );
                }
                serde_json::to_string_pretty(&val)
                    .map_err(|e| McpError::internal_error(e.to_string(), None))?
            }
            None => serde_json::to_string_pretty(&execution)
                .map_err(|e| McpError::internal_error(e.to_string(), None))?,
        };

        Ok(CallToolResult {
            content: vec![Content::text(output)],
            structured_content: None,
            is_error: Some(is_error),
            meta: None,
        })
    }

    #[tool(
        name = "logs",
        description = "Retrieve execution logs. Returns recent task execution results.",
        annotations(
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn logs(
        &self,
        Parameters(req): Parameters<LogsRequest>,
    ) -> Result<CallToolResult, McpError> {
        let output = match req.task_id.as_deref() {
            Some(id) => {
                match self.log_store.get(id) {
                    None => {
                        return Err(McpError::internal_error(
                            format!("execution not found: {id}"),
                            None,
                        ));
                    }
                    Some(mut execution) => {
                        // Apply tail filter if requested
                        if let Some(n) = req.tail {
                            execution.stdout = tail_lines(&execution.stdout, n);
                        }
                        serde_json::to_string_pretty(&execution)
                            .map_err(|e| McpError::internal_error(e.to_string(), None))?
                    }
                }
            }
            None => {
                let summaries = self.log_store.recent(10);
                serde_json::to_string_pretty(&summaries)
                    .map_err(|e| McpError::internal_error(e.to_string(), None))?
            }
        };

        Ok(CallToolResult {
            content: vec![Content::text(output)],
            structured_content: None,
            is_error: Some(false),
            meta: None,
        })
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
impl TaskMcpServer {
    /// Set the workdir directly (test-only helper).
    pub(crate) async fn set_workdir_for_test(&self, path: PathBuf) {
        *self.workdir.write().await = Some(path);
    }

    /// Read the current workdir (test-only helper).
    pub(crate) async fn current_workdir(&self) -> Option<PathBuf> {
        self.workdir.read().await.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // -------------------------------------------------------------------------
    // GroupMatcher
    // -------------------------------------------------------------------------

    #[test]
    fn group_matcher_exact() {
        let m = GroupMatcher::new("profile");
        assert!(m.is_match("profile"));
        assert!(!m.is_match("profiler"));
        assert!(!m.is_match("agent"));
    }

    #[test]
    fn group_matcher_star_prefix() {
        let m = GroupMatcher::new("prof*");
        assert!(m.is_match("profile"));
        assert!(m.is_match("profiler"));
        assert!(m.is_match("prof"));
        assert!(!m.is_match("agent"));
    }

    #[test]
    fn group_matcher_star_suffix() {
        let m = GroupMatcher::new("*-release");
        assert!(m.is_match("build-release"));
        assert!(m.is_match("test-release"));
        assert!(!m.is_match("release-build"));
    }

    #[test]
    fn group_matcher_star_middle() {
        let m = GroupMatcher::new("ci-*-fast");
        assert!(m.is_match("ci-build-fast"));
        assert!(m.is_match("ci--fast"));
        assert!(!m.is_match("ci-build-slow"));
    }

    #[test]
    fn group_matcher_question_mark() {
        let m = GroupMatcher::new("ci-?");
        assert!(m.is_match("ci-1"));
        assert!(m.is_match("ci-a"));
        assert!(!m.is_match("ci-"));
        assert!(!m.is_match("ci-12"));
    }

    #[test]
    fn group_matcher_special_chars_escaped() {
        // Regex metacharacters in the pattern must be treated literally.
        let m = GroupMatcher::new("ci.release+1");
        assert!(m.is_match("ci.release+1"));
        assert!(!m.is_match("ciXreleaseX1"));
    }

    fn make_server(server_cwd: PathBuf) -> TaskMcpServer {
        TaskMcpServer::new(Config::default(), server_cwd)
    }

    fn make_server_with_allowed_dirs(
        server_cwd: PathBuf,
        allowed_dirs: Vec<PathBuf>,
    ) -> TaskMcpServer {
        let config = Config {
            allowed_dirs,
            ..Config::default()
        };
        TaskMcpServer::new(config, server_cwd)
    }

    // -------------------------------------------------------------------------
    // try_auto_session_start
    // -------------------------------------------------------------------------

    /// .git ディレクトリがある ProjectRoot で auto-start が成功する。
    #[tokio::test]
    async fn test_try_auto_session_start_in_project_root() {
        let tmpdir = tempfile::tempdir().expect("create tempdir");
        std::fs::create_dir(tmpdir.path().join(".git")).expect("create .git dir");

        let server = make_server(tmpdir.path().to_path_buf());
        let outcome = server.try_auto_session_start().await;

        match outcome {
            AutoStartOutcome::Started(resp, _wd) => {
                assert_eq!(resp.mode, "agent-only");
            }
            other => panic!("auto-start should succeed in a ProjectRoot (.git), got {other:?}"),
        }
        assert!(
            server.current_workdir().await.is_some(),
            "workdir should be set after auto-start"
        );
    }

    /// 2回目の呼び出しでは auto-start が発生しない (already started)。
    #[tokio::test]
    async fn test_second_call_no_auto_start() {
        let tmpdir = tempfile::tempdir().expect("create tempdir");
        std::fs::create_dir(tmpdir.path().join(".git")).expect("create .git dir");

        let server = make_server(tmpdir.path().to_path_buf());

        // 1回目: auto-start 発生
        let (_, auto1) = server
            .workdir_or_auto()
            .await
            .expect("first call should succeed");
        assert!(auto1.is_some(), "first call should trigger auto-start");

        // 2回目: workdir は既に設定済み → auto なし
        let (_, auto2) = server
            .workdir_or_auto()
            .await
            .expect("second call should succeed");
        assert!(
            auto2.is_none(),
            "second call must NOT return auto_session_start"
        );
    }

    /// marker なし (非 ProjectRoot) では auto-start しない → error。
    #[tokio::test]
    async fn test_no_auto_start_in_non_project_root() {
        let tmpdir = tempfile::tempdir().expect("create tempdir");
        // .git も justfile も作成しない

        let server = make_server(tmpdir.path().to_path_buf());
        let result = server.workdir_or_auto().await;

        let err = result.expect_err("should fail when no ProjectRoot marker");
        assert!(
            err.message.contains("not a ProjectRoot"),
            "error message should identify 'not a ProjectRoot': {err:?}"
        );
    }

    /// justfile のみ存在する場合でも auto-start が成功する。
    #[tokio::test]
    async fn test_justfile_marker_also_triggers() {
        let tmpdir = tempfile::tempdir().expect("create tempdir");
        // .git はなく justfile のみ
        std::fs::write(tmpdir.path().join("justfile"), "").expect("create justfile");

        let server = make_server(tmpdir.path().to_path_buf());
        let outcome = server.try_auto_session_start().await;

        assert!(
            matches!(outcome, AutoStartOutcome::Started(_, _)),
            "auto-start should succeed with only justfile marker, got {outcome:?}"
        );
    }

    /// allowed_dirs 違反の場合は auto-start しない → error (原因が区別される)。
    #[tokio::test]
    async fn test_allowed_dirs_violation_no_auto_start() {
        let tmpdir = tempfile::tempdir().expect("create tempdir");
        std::fs::create_dir(tmpdir.path().join(".git")).expect("create .git dir");

        let other_dir = tempfile::tempdir().expect("create other tempdir");
        let allowed = vec![other_dir.path().to_path_buf()];

        let server = make_server_with_allowed_dirs(tmpdir.path().to_path_buf(), allowed);
        let err = server
            .workdir_or_auto()
            .await
            .expect_err("should fail when server_cwd is not in allowed_dirs");
        assert!(
            err.message.contains("allowed_dirs"),
            "error message should identify the allowed_dirs violation: {err:?}"
        );
    }

    /// HIGH-1 regression: `try_auto_session_start` が並行初期化済みの状態で
    /// `AlreadyStarted` を返し、`workdir_or_auto` 経由では誤エラーにならない。
    #[tokio::test]
    async fn test_auto_start_already_started_variant() {
        let tmpdir = tempfile::tempdir().expect("create tempdir");
        std::fs::create_dir(tmpdir.path().join(".git")).expect("create .git dir");

        let server = make_server(tmpdir.path().to_path_buf());

        // 並行初期化を模倣: 直接 workdir を設定してから slow path を叩く。
        let pre_set = tmpdir.path().join("pre-set");
        std::fs::create_dir(&pre_set).expect("create pre-set dir");
        server.set_workdir_for_test(pre_set.clone()).await;

        let outcome = server.try_auto_session_start().await;
        match outcome {
            AutoStartOutcome::AlreadyStarted(wd) => assert_eq!(wd, pre_set),
            other => panic!("expected AlreadyStarted, got {other:?}"),
        }
    }

    /// ProjectRoot でも明示 session_start (workdir=subdir) 後には auto がない。
    #[tokio::test]
    async fn test_explicit_session_start_overrides() {
        let tmpdir = tempfile::tempdir().expect("create tempdir");
        std::fs::create_dir(tmpdir.path().join(".git")).expect("create .git dir");

        // subdir を作って明示的に workdir をセット
        let subdir = tmpdir.path().join("subdir");
        std::fs::create_dir(&subdir).expect("create subdir");

        let server = make_server(tmpdir.path().to_path_buf());
        // 明示的な session_start を模倣して workdir を直接セット
        server.set_workdir_for_test(subdir.clone()).await;

        // workdir_or_auto を呼んでも auto は発生しない (already started)
        let result = server.workdir_or_auto().await;
        assert!(result.is_ok());
        let (wd, auto) = result.unwrap();
        assert!(
            auto.is_none(),
            "after explicit session_start, auto_session_start must be None"
        );
        // workdir は subdir (server_cwd ではない)
        assert_eq!(
            wd, subdir,
            "workdir should be the explicitly set subdir, not server_cwd"
        );
    }
}