troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
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
use std::{
    borrow::Cow,
    io,
    net::IpAddr,
    num::{NonZeroU16, NonZeroU32},
};

use rmcp::{
    ErrorData, RoleServer, ServerHandler, ServiceExt,
    handler::server::{
        tool::{ToolCallContext, ToolRouter},
        wrapper::Parameters,
    },
    model::{
        CallToolRequestMethod, CallToolRequestParams, CallToolResponse, CallToolResult,
        ConstString, CustomRequest, CustomResult, ErrorCode, Implementation, ProtocolVersion,
        ServerCapabilities, ServerConfig,
    },
    schemars::{self, JsonSchema},
    service::{QuitReason, RequestContext, ServerInitializeError},
    tool, tool_handler, tool_router,
};
use serde::{Deserialize, Deserializer, Serialize};
use time::{OffsetDateTime, SignedDuration};
use tokio::{runtime::Builder, task::spawn_blocking};
use troll_core::{Zone, ZoneChanges, parse_duration};

use crate::{
    cli::{
        AppAllocationArgs, ClaimArgs, EditArgs, KindArg, LeaseArgs, RoleArg, WebArgs, WebScheme,
    },
    commands::{
        Context, app, edit, history, inspect, list, registry,
        timestamp::deserialize_required_leased_at, zone,
    },
    error::{CliError, ErrorOutput},
    json_object::JsonObject,
};

const PRIMARY_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::V_2026_07_28;
const SUPPORTED_PROTOCOL_VERSIONS: &[ProtocolVersion] =
    &[PRIMARY_PROTOCOL_VERSION, ProtocolVersion::V_2025_11_25];

#[derive(Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
enum KindFilter {
    Ours,
    System,
    ThirdParty,
}

impl From<KindFilter> for KindArg {
    fn from(kind: KindFilter) -> Self {
        match kind {
            KindFilter::Ours => Self::Ours,
            KindFilter::System => Self::System,
            KindFilter::ThirdParty => Self::ThirdParty,
        }
    }
}

#[derive(Default, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
enum PortRole {
    #[default]
    App,
    Service,
}

impl From<PortRole> for RoleArg {
    fn from(role: PortRole) -> Self {
        match role {
            PortRole::App => Self::App,
            PortRole::Service => Self::Service,
        }
    }
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct CheckInput {
    #[serde(deserialize_with = "deserialize_port")]
    port: NonZeroU16,
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ListInput {
    #[serde(deserialize_with = "deserialize_kind", default)]
    kind: Option<KindFilter>,
    #[serde(deserialize_with = "deserialize_role", default)]
    role: Option<PortRole>,
    #[serde(deserialize_with = "deserialize_drift", default)]
    drift: bool,
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct LeaseInput {
    #[serde(deserialize_with = "deserialize_project")]
    project: String,
    #[serde(deserialize_with = "deserialize_purpose")]
    purpose: String,
    /// Positive integer followed by s, m, h or d, such as 2h. Defaults to the configured lease duration.
    #[serde(default, deserialize_with = "deserialize_duration")]
    #[schemars(with = "Option<String>", regex(pattern = "^[0-9]*[1-9][0-9]*[smhd]$"))]
    duration: Option<SignedDuration>,
    /// Optional process ID that informs lease reclamation.
    #[serde(deserialize_with = "deserialize_pid", default)]
    pid: Option<NonZeroU32>,
    #[serde(deserialize_with = "deserialize_bind", default)]
    bind: Option<IpAddr>,
    /// Component names for a temporary stack. Keep the returned group ID for renew and release.
    #[serde(deserialize_with = "deserialize_group", default)]
    group: Option<Vec<String>>,
    /// Optional named pool configured under [pools] in config.toml.
    #[serde(deserialize_with = "deserialize_pool", default)]
    pool: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(extend("oneOf" = serde_json::json!([
    {"required": ["port", "leased_at"], "not": {"required": ["group"]}},
    {"required": ["group"], "not": {"anyOf": [{"required": ["port"]}, {"required": ["leased_at"]}]}},
])))]
struct RenewInput {
    #[serde(default, deserialize_with = "deserialize_target_port")]
    #[schemars(with = "NonZeroU16")]
    port: Option<NonZeroU16>,
    /// Group ID returned when the stack was leased.
    #[serde(default, deserialize_with = "deserialize_present")]
    #[schemars(with = "String")]
    group: Option<String>,
    /// Positive integer followed by s, m, h or d, such as 2h. Defaults to the configured lease duration.
    #[serde(default, deserialize_with = "deserialize_duration")]
    #[schemars(with = "Option<String>", regex(pattern = "^[0-9]*[1-9][0-9]*[smhd]$"))]
    duration: Option<SignedDuration>,
    /// Original RFC 3339 lease identity from troll. Required with port.
    #[serde(default, deserialize_with = "deserialize_target_leased_at")]
    #[schemars(with = "String")]
    leased_at: Option<OffsetDateTime>,
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(extend("oneOf" = serde_json::json!([
    {"required": ["port", "leased_at"], "not": {"anyOf": [{"required": ["group"]}, {"required": ["claim"]}]}},
    {"required": ["group"], "not": {"anyOf": [{"required": ["port"]}, {"required": ["leased_at"]}, {"required": ["claim"]}]}},
    {"required": ["claim"], "not": {"anyOf": [{"required": ["port"]}, {"required": ["leased_at"]}, {"required": ["group"]}]}},
])))]
struct ReleaseInput {
    #[serde(default, deserialize_with = "deserialize_target_port")]
    #[schemars(with = "NonZeroU16")]
    port: Option<NonZeroU16>,
    /// Original RFC 3339 lease identity from troll. Required with port.
    #[serde(default, deserialize_with = "deserialize_target_leased_at")]
    #[schemars(with = "String")]
    leased_at: Option<OffsetDateTime>,
    /// Group ID returned when the stack was leased.
    #[serde(default, deserialize_with = "deserialize_present")]
    #[schemars(with = "String")]
    group: Option<String>,
    /// Release a permanent claim.
    #[serde(default, deserialize_with = "deserialize_release_claim")]
    #[schemars(with = "ReleaseClaimInput")]
    claim: Option<JsonObject<ReleaseClaimInput>>,
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ReleaseClaimInput {
    #[serde(deserialize_with = "deserialize_port")]
    port: NonZeroU16,
    /// Permit release of a service with dependent projects.
    #[serde(default)]
    force_shared: bool,
    /// Optional tag returned by troll_check for the confirmed claim.
    tag: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct ClaimInput {
    #[serde(deserialize_with = "deserialize_port")]
    port: NonZeroU16,
    #[serde(deserialize_with = "deserialize_project")]
    project: String,
    #[serde(deserialize_with = "deserialize_service")]
    service: String,
    #[serde(deserialize_with = "deserialize_role", default)]
    role: Option<PortRole>,
    #[serde(deserialize_with = "deserialize_bind", default)]
    bind: Option<IpAddr>,
    #[serde(deserialize_with = "deserialize_container", default)]
    container: Option<String>,
    #[serde(deserialize_with = "deserialize_used_by", default)]
    used_by: Option<Vec<String>>,
    /// Local web path, such as /admin.
    web: Option<String>,
    web_scheme: Option<WebScheme>,
    component: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct EditInput {
    #[serde(deserialize_with = "deserialize_port")]
    port: NonZeroU16,
    /// The entry tag returned by troll_check.
    tag: String,
    #[serde(deserialize_with = "deserialize_edit_fields")]
    #[schemars(with = "EditFields")]
    changes: JsonObject<EditFields>,
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct EditFields {
    service: Option<String>,
    role: Option<PortRole>,
    bind: Option<IpAddr>,
    used_by: Option<Vec<String>>,
    #[serde(default)]
    clear_used_by: bool,
    /// Set the container name or pass null to clear it.
    #[serde(default, deserialize_with = "edit::deserialize_nullable_string")]
    #[schemars(with = "Option<String>")]
    container: Option<Option<String>>,
    /// Local web path, such as /admin.
    web: Option<String>,
    web_scheme: Option<WebScheme>,
    #[serde(default)]
    no_web: bool,
    component: Option<String>,
    #[serde(default)]
    no_component: bool,
}

impl TryFrom<EditFields> for edit::EditChanges {
    type Error = CliError;

    fn try_from(fields: EditFields) -> Result<Self, Self::Error> {
        EditArgs {
            tag: None,
            service: fields.service,
            role: fields.role.map(Into::into),
            bind: fields.bind,
            used_by: fields.used_by,
            clear_used_by: fields.clear_used_by,
            clear_container: fields.container == Some(None),
            container: fields.container.flatten(),
            web: WebArgs {
                web: fields.web,
                web_scheme: fields.web_scheme,
            },
            no_web: fields.no_web,
            component: fields.component,
            no_component: fields.no_component,
        }
        .try_into()
    }
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct LeaseEditInput {
    #[serde(deserialize_with = "deserialize_port")]
    port: NonZeroU16,
    /// The entry tag returned by troll_check.
    tag: String,
    purpose: Option<String>,
    /// Positive integer followed by s, m, h or d, such as 2h. Omit to keep the current expiry.
    #[serde(default, deserialize_with = "deserialize_duration")]
    #[schemars(with = "Option<String>", regex(pattern = "^[0-9]*[1-9][0-9]*[smhd]$"))]
    duration: Option<SignedDuration>,
}

#[derive(Deserialize, JsonSchema)]
#[serde(tag = "action", rename_all = "lowercase", deny_unknown_fields)]
#[schemars(extend("type" = "object"))]
enum ZoneInput {
    Add {
        label: String,
        /// Single ports and inclusive ranges, for example ["0-1023", "8080"].
        ports: Vec<String>,
        reason: Option<String>,
        #[serde(default)]
        disabled: bool,
    },
    List {},
    Enable {
        label: String,
    },
    Disable {
        label: String,
    },
    Edit {
        label: String,
        /// The zone tag returned by troll_zone list.
        tag: String,
        /// Omit to keep the reason or pass null to clear it.
        #[serde(default, deserialize_with = "edit::deserialize_nullable_string")]
        #[schemars(with = "Option<String>")]
        reason: Option<Option<String>>,
        /// Replacement port list. Omit to keep the current ranges.
        ports: Option<Vec<String>>,
    },
    Remove {
        label: String,
        /// Optional tag returned by troll_zone list for the confirmed zone.
        tag: Option<String>,
    },
}

#[derive(Deserialize, JsonSchema)]
#[serde(tag = "action", rename_all = "lowercase", deny_unknown_fields)]
#[schemars(extend("type" = "object"))]
enum HistoryInput {
    List {},
    Show { id: String },
    Restore { id: String },
}

#[derive(Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct AppAllocationInput {
    app: String,
    /// Component names, with :service for supporting services.
    components: Vec<String>,
    /// Optional pins in COMPONENT=PORT form.
    #[serde(default)]
    pins: Vec<String>,
    bind: Option<IpAddr>,
}

impl From<AppAllocationInput> for AppAllocationArgs {
    fn from(input: AppAllocationInput) -> Self {
        Self {
            app: input.app,
            components: input.components,
            pins: input.pins,
            bind: input.bind,
        }
    }
}

#[derive(Deserialize, JsonSchema)]
#[serde(tag = "action", rename_all = "lowercase", deny_unknown_fields)]
#[schemars(extend("type" = "object"))]
enum AppInput {
    Reserve(AppAllocationInput),
    Show {
        app: String,
    },
    Add(AppAllocationInput),
    Remove {
        app: String,
        component: String,
        #[serde(default)]
        force_shared: bool,
        /// Optional tag returned by troll_check or troll_app show for the confirmed component.
        tag: Option<String>,
    },
    Edit {
        app: String,
        component: String,
        /// The component's entry tag returned by troll_check.
        tag: String,
        #[serde(deserialize_with = "deserialize_edit_fields")]
        #[schemars(with = "EditFields")]
        changes: JsonObject<EditFields>,
    },
    Release {
        app: String,
        /// The app name, typed again to confirm release.
        confirm: String,
        /// Optional app tag returned by troll_app show for the confirmed membership.
        tag: Option<String>,
    },
}

// Serde's value errors do not identify the field on a JSON object. Add that
// context at each input boundary so clients can correct a rejected argument.
macro_rules! field_deserializer {
    ($($function:ident => $field:literal),+ $(,)?) => {$ (
        fn $function<'de, D, T>(deserializer: D) -> Result<T, D::Error>
        where
            D: Deserializer<'de>,
            T: Deserialize<'de>,
        {
            T::deserialize(deserializer)
                .map_err(|error| serde::de::Error::custom(format!("{}: {error}", $field)))
        }
    )+};
}

field_deserializer! {
    deserialize_port => "port",
    deserialize_kind => "kind",
    deserialize_role => "role",
    deserialize_drift => "drift",
    deserialize_project => "project",
    deserialize_service => "service",
    deserialize_purpose => "purpose",
    deserialize_pid => "pid",
    deserialize_bind => "bind",
    deserialize_container => "container",
    deserialize_used_by => "used_by",
    deserialize_group => "group",
    deserialize_pool => "pool",
}

fn deserialize_duration<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<SignedDuration>, D::Error> {
    let duration = Option::<String>::deserialize(deserializer)
        .map_err(|error| serde::de::Error::custom(format!("duration: {error}")))?;
    duration
        .as_deref()
        .map(parse_duration)
        .transpose()
        .map_err(|error| serde::de::Error::custom(format!("duration: {error}")))
}

fn deserialize_present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    T::deserialize(deserializer).map(Some)
}

// Serde errors can contain fragments of the submitted arguments.
fn deserialize_release_claim<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<JsonObject<ReleaseClaimInput>>, D::Error> {
    deserialize_present(deserializer).map_err(|_| {
        serde::de::Error::custom("invalid claim: expected an object matching the input schema")
    })
}

fn deserialize_edit_fields<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<JsonObject<EditFields>, D::Error> {
    JsonObject::deserialize(deserializer).map_err(|_| {
        serde::de::Error::custom("invalid changes: expected an object matching the input schema")
    })
}

fn deserialize_target_port<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<NonZeroU16>, D::Error> {
    deserialize_port(deserializer).map(Some)
}

fn deserialize_target_leased_at<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<OffsetDateTime>, D::Error> {
    deserialize_required_leased_at(deserializer).map(Some)
}

struct TrollServer {
    tool_router: ToolRouter<Self>,
}

#[tool_router]
impl TrollServer {
    #[tool(
        description = "Check whether a fixed port is registered or listening before you bind it. Tests bind port 0 so the operating system chooses the port. Tests never lease."
    )]
    async fn troll_check(
        &self,
        Parameters(input): Parameters<CheckInput>,
    ) -> Result<CallToolResult, ErrorData> {
        run_tool(move |context| inspect::build_tagged_check(context, input.port.get())).await
    }

    #[tool(
        description = "See registered ports and live listeners. Set drift to true to see where they differ. Tests bind port 0 and never lease."
    )]
    async fn troll_list(
        &self,
        Parameters(input): Parameters<ListInput>,
    ) -> Result<CallToolResult, ErrorData> {
        let kind = input.kind.map(|kind| KindArg::from(kind).into());
        let role = input.role.map(|role| RoleArg::from(role).into());
        if input.drift {
            run_tool(move |context| list::build_drift(context, kind, role)).await
        } else {
            run_tool(move |context| inspect::build_list(context, kind, role)).await
        }
    }

    #[tool(
        description = "Lease the lowest free port in the configured range, or set group to lease one \
                       port per component. For a group, keep the returned ID for troll_renew or \
                       troll_release. For a single port, keep the leased_at from your own lease reply to renew or release. If you no longer have it, let the \
                       lease expire. \
                       Durations above the maximum are refused. A sweep reclaims a silent port \
                       after expiry, or earlier if the supplied pid has exited. Tests bind port 0 \
                       and never lease. If a lease reply was lost, do not renew or release any lease \
                       you find. Take a new lease if needed and let the unknown one expire. \
                       Run troll sweep to reclaim silent expired leases."
    )]
    async fn troll_lease(
        &self,
        Parameters(input): Parameters<LeaseInput>,
    ) -> Result<CallToolResult, ErrorData> {
        let args = LeaseArgs {
            project: input.project,
            purpose: input.purpose,
            duration: input.duration,
            pid: input.pid.map(NonZeroU32::get),
            bind: input.bind,
            pool: input.pool,
        };
        if let Some(components) = input.group {
            run_tool(move |context| registry::build_lease_group(context, args, components)).await
        } else {
            run_tool(move |context| registry::build_lease(context, args)).await
        }
    }

    #[tool(
        description = "Set expiry to now plus the duration (configured default if omitted, capped \
                       at the configured maximum). A shorter duration can shorten the lease. \
                       Use group to renew an entire stack under the server's holder. For a single port, \
                       pass the leased_at from your own lease reply. If you no longer have it, \
                       let the lease expire. Tests bind port 0 and never lease. After cancellation, timeout \
                       or failure, wait for the lock timeout (10 seconds by default), then use \
                       troll_check or troll_list. A negative snapshot may precede the call reaching \
                       the lock. Check again later. For a single lease, retry only with the same \
                       leased_at. A different leased_at identifies a replacement. Leave it alone. If a lease reply was \
                       lost, do not renew or release any lease you find. Take a new lease if needed \
                       and let the unknown one expire. Run troll sweep to reclaim silent expired leases."
    )]
    async fn troll_renew(
        &self,
        Parameters(input): Parameters<RenewInput>,
    ) -> Result<CallToolResult, ErrorData> {
        match (input.port, input.leased_at, input.group) {
            (Some(port), Some(leased_at), None) => {
                run_tool(move |context| {
                    registry::build_renew(context, port.get(), input.duration, Some(leased_at))
                })
                .await
            }
            (None, None, Some(group)) => {
                run_tool(move |context| registry::build_renew_group(context, group, input.duration))
                    .await
            }
            _ => tool_error(
                "InvalidRequest",
                "supply either port and leased_at, or group",
                2,
            ),
        }
    }

    #[tool(
        description = "Release a single lease using the leased_at from your own lease reply. \
                       If you no longer have it, let the lease expire. Use group to release an entire \
                       stack under the server's holder. Use claim to release a permanent port. \
                       Include the claim's tag from troll_check to release the version you confirmed. \
                       After cancellation, timeout or failure, wait for the lock \
                       timeout (10 seconds by default), then use troll_check or troll_list. A negative \
                       snapshot may precede the call reaching the lock. Check again later. \
                       For a single lease, retry only with the same leased_at. A different leased_at \
                       identifies a replacement. Leave it alone. If a lease reply was lost, do not renew \
                       or release any lease you find. Take a new lease if needed and let the unknown \
                       one expire. Run troll sweep to reclaim silent expired leases."
    )]
    async fn troll_release(
        &self,
        Parameters(input): Parameters<ReleaseInput>,
    ) -> Result<CallToolResult, ErrorData> {
        match (input.port, input.leased_at, input.group, input.claim) {
            (Some(port), Some(leased_at), None, None) => {
                run_tool(move |context| {
                    registry::build_release_lease(context, port.get(), Some(leased_at), None)
                })
                .await
            }
            (None, None, Some(group), None) => {
                run_tool(move |context| registry::build_release_group(context, group, None)).await
            }
            (None, None, None, Some(JsonObject(claim))) => {
                run_tool(move |context| {
                    registry::build_release_claim(
                        context,
                        claim.port.get(),
                        claim.force_shared,
                        claim.tag.as_deref(),
                    )
                })
                .await
            }
            _ => tool_error(
                "InvalidRequest",
                "supply exactly one of port and leased_at, group, or claim",
                2,
            ),
        }
    }

    #[tool(
        description = "Register a project's long-lived service or app port permanently. Tests \
                       bind port 0 and never lease. After cancellation, \
                       timeout or failure, wait for the lock timeout (10 seconds by default), then \
                       use troll_check. A negative snapshot may precede the call reaching the lock. \
                       Check again later. Renew or release only with the leased_at from your own \
                       lease reply. If you no longer have it, let the lease expire. If a lease reply \
                       was lost, do not renew or release any lease you find. Take a new lease if needed \
                       and let the unknown one expire. \
                       Run troll sweep to reclaim silent expired leases."
    )]
    async fn troll_claim(
        &self,
        Parameters(input): Parameters<ClaimInput>,
    ) -> Result<CallToolResult, ErrorData> {
        let args = ClaimArgs {
            port: input.port.get(),
            project: input.project,
            service: input.service,
            role: input.role.unwrap_or_default().into(),
            bind: input.bind,
            container: input.container,
            used_by: input.used_by,
            web: WebArgs {
                web: input.web,
                web_scheme: input.web_scheme,
            },
            component: input.component,
        };
        run_tool(move |context| registry::build_claim(context, args)).await
    }

    #[tool(
        description = "Edit, never release and re-claim, to change a permanent entry. Read the entry's tag \
                       with troll_check first. On a stale tag, read again and retry only if the change \
                       still makes sense. After a timeout or other failure, check the current entry before \
                       retrying. Tests bind port 0 and never claim."
    )]
    async fn troll_edit(
        &self,
        Parameters(input): Parameters<EditInput>,
    ) -> Result<CallToolResult, ErrorData> {
        let JsonObject(changes) = input.changes;
        run_tool(move |context| {
            edit::build_edit(
                context,
                input.port.get(),
                Some(&input.tag),
                changes.try_into()?,
            )
        })
        .await
    }

    #[tool(
        description = "Edit a lease in place to change its purpose or expiry. Read the entry's tag with \
                       troll_check first. On a stale tag, read again and retry only if the change still \
                       makes sense. After a timeout or other failure, check that you still have the same \
                       lease before retrying. Edit, never release and re-claim. Tests bind port 0 and \
                       never lease."
    )]
    async fn troll_lease_edit(
        &self,
        Parameters(input): Parameters<LeaseEditInput>,
    ) -> Result<CallToolResult, ErrorData> {
        run_tool(move |context| {
            edit::build_lease_edit(
                context,
                input.port.get(),
                Some(&input.tag),
                input.purpose,
                input.duration,
            )
        })
        .await
    }

    #[tool(
        description = "Add, list, edit, enable, disable or remove red zones for future port allocations. \
                       Edit requires the zone tag from list. Use that tag to remove the confirmed zone. \
                       Review any reported conflicts with existing claims or leases. After a failure, \
                       list the zones to confirm the current policy before retrying. Tests bind port 0."
    )]
    async fn troll_zone(
        &self,
        Parameters(input): Parameters<ZoneInput>,
    ) -> Result<CallToolResult, ErrorData> {
        match input {
            ZoneInput::Add {
                label,
                ports,
                reason,
                disabled,
            } => {
                run_tool(move |context| {
                    zone::build_zone_add(
                        context,
                        Zone {
                            label,
                            ports,
                            reason,
                            enabled: !disabled,
                        },
                    )
                })
                .await
            }
            ZoneInput::List {} => run_tool(zone::build_zone_list).await,
            ZoneInput::Enable { label } => {
                run_tool(move |context| zone::build_zone_enabled(context, &label, true)).await
            }
            ZoneInput::Disable { label } => {
                run_tool(move |context| zone::build_zone_enabled(context, &label, false)).await
            }
            ZoneInput::Edit {
                label,
                tag,
                reason,
                ports,
            } => {
                run_tool(move |context| {
                    zone::build_zone_edit_if_match(
                        context,
                        &label,
                        &tag,
                        ZoneChanges { reason, ports },
                        None,
                    )
                })
                .await
            }
            ZoneInput::Remove { label, tag } => {
                run_tool(move |context| zone::build_zone_remove(context, &label, tag.as_deref()))
                    .await
            }
        }
    }

    #[tool(
        description = "Reserve several permanent ports for a new app, show its entries, or add, remove \
                       or edit a component. To release the whole app, pass its name again in confirm. \
                       Use the app tag or component tag from show to release the version you confirmed. \
                       After a failure, show the app before retrying. Edit, never release and re-claim. \
                       For an edit, read the entry's tag with troll_check first. On a stale tag, read \
                       again and retry only if the change still makes sense. Tests bind port 0."
    )]
    async fn troll_app(
        &self,
        Parameters(input): Parameters<AppInput>,
    ) -> Result<CallToolResult, ErrorData> {
        match input {
            AppInput::Reserve(args) => {
                run_tool(move |context| app::build_app_reserve(context, args.into())).await
            }
            AppInput::Show { app } => {
                run_tool(move |context| app::build_app_show(context, &app)).await
            }
            AppInput::Add(args) => {
                run_tool(move |context| app::build_app_add(context, args.into())).await
            }
            AppInput::Remove {
                app,
                component,
                force_shared,
                tag,
            } => {
                run_tool(move |context| {
                    app::build_app_remove(context, &app, &component, force_shared, tag.as_deref())
                })
                .await
            }
            AppInput::Edit {
                app,
                component,
                tag,
                changes: JsonObject(changes),
            } => {
                run_tool(move |context| {
                    app::build_app_edit(context, &app, &component, Some(&tag), changes.try_into()?)
                })
                .await
            }
            AppInput::Release { app, confirm, tag } => {
                run_tool(move |context| {
                    app::build_app_release(context, &app, &confirm, tag.as_deref())
                })
                .await
            }
        }
    }

    #[tool(
        description = "List, inspect, or restore apps, permanent claims, and leases removed within the last 30 days. \
                       Restore checks port availability and enabled red zones under the lock and refuses on conflict. \
                       Tests bind port 0."
    )]
    async fn troll_history(
        &self,
        Parameters(input): Parameters<HistoryInput>,
    ) -> Result<CallToolResult, ErrorData> {
        match input {
            HistoryInput::List {} => run_tool(history::build_history_list).await,
            HistoryInput::Show { id } => {
                run_tool(move |context| history::build_history_show(context, &id)).await
            }
            HistoryInput::Restore { id } => {
                run_tool(move |context| history::build_history_restore(context, &id)).await
            }
        }
    }
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for TrollServer {
    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, ErrorData> {
        let route = self
            .tool_router
            .map
            .get(request.name.as_ref())
            .ok_or_else(|| ErrorData::invalid_params("tool not found", None))?;
        // Keep unknown tools as protocol errors. Convert only rmcp's typed
        // argument extraction errors into troll's structured tool error envelope.
        match (route.call)(ToolCallContext::new(self, request, context)).await {
            Err(error)
                if error.code == ErrorCode::INVALID_PARAMS
                    && error
                        .message
                        .starts_with("failed to deserialize parameters:") =>
            {
                tool_error("InvalidRequest", &error.message, 2).map(Into::into)
            }
            result => result,
        }
    }

    async fn on_custom_request(
        &self,
        request: CustomRequest,
        _context: RequestContext<RoleServer>,
    ) -> Result<CustomResult, ErrorData> {
        // rmcp falls back to CustomRequest for malformed tools/call envelopes.
        if request.method == CallToolRequestMethod::VALUE {
            return Err(ErrorData::invalid_params(
                "invalid tools/call parameters",
                None,
            ));
        }
        Err(ErrorData::new(
            ErrorCode::METHOD_NOT_FOUND,
            request.method,
            None,
        ))
    }

    fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
        Cow::Borrowed(SUPPORTED_PROTOCOL_VERSIONS)
    }

    fn get_info(&self) -> ServerConfig {
        ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
            .with_protocol_version(PRIMARY_PROTOCOL_VERSION)
            .with_server_info(Implementation::new("troll", env!("CARGO_PKG_VERSION")))
            .with_instructions(
                "Claim a port for a long-lived service or app that belongs in the registry. \
                 Lease a port when a temporary process needs a known port. \
                 Tests bind port 0 and let the operating system choose.",
            )
    }
}

async fn run_tool<T: Serialize>(
    build: impl FnOnce(&Context) -> Result<T, CliError> + Send + 'static,
) -> Result<CallToolResult, ErrorData> {
    // Load config per call, as the CLI does, so config errors are tool results.
    let result = spawn_blocking(move || {
        let context = Context::load()?;
        serde_json::to_value(build(&context)?).map_err(CliError::Json)
    })
    .await
    .unwrap_or_else(|error| Err(service_error("run the MCP tool", error)));
    match result {
        Ok(value) => Ok(CallToolResult::structured(value)),
        Err(error) => {
            let (kind, exit_code) = error.kind_and_code();
            let message = error.to_string();
            tool_error(kind, message.trim_end(), exit_code)
        }
    }
}

fn tool_error(
    kind: &'static str,
    message: &str,
    exit_code: u8,
) -> Result<CallToolResult, ErrorData> {
    serde_json::to_value(ErrorOutput::new(kind, message, exit_code))
        .map(CallToolResult::structured_error)
        .map_err(|error| ErrorData::internal_error(error.to_string(), None))
}

pub(crate) fn run() -> Result<(), CliError> {
    let runtime = Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|error| CliError::Serve("start the MCP runtime", error))?;
    runtime.block_on(serve_stdio())
}

async fn serve_stdio() -> Result<(), CliError> {
    let server = TrollServer {
        tool_router: TrollServer::tool_router(),
    };
    let service = match server.serve(rmcp::transport::stdio_pipes()).await {
        Ok(service) => service,
        Err(ServerInitializeError::ConnectionClosed(_)) => return Ok(()),
        Err(error) => return Err(service_error("initialize the MCP server", error)),
    };
    match service.waiting().await {
        Ok(QuitReason::JoinError(error)) | Err(error) => {
            Err(service_error("run the MCP server", error))
        }
        Ok(_) => Ok(()),
    }
}

fn service_error(
    operation: &'static str,
    error: impl Into<Box<dyn std::error::Error + Send + Sync>>,
) -> CliError {
    CliError::Serve(operation, io::Error::other(error))
}

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

    #[test]
    fn action_tools_publish_object_schemas_and_require_action_specific_fields() {
        let router = TrollServer::tool_router();
        for tool in ["troll_app", "troll_zone"] {
            let schema = &router.map[tool].attr.input_schema;
            assert_eq!(schema["type"], "object");
            assert!(schema["oneOf"].is_array());
        }

        let app: AppInput = serde_json::from_value(json!({
            "action": "reserve", "app": "demo", "components": ["api", "db:service"],
        }))
        .unwrap();
        assert!(matches!(app, AppInput::Reserve(_)));
        assert!(
            serde_json::from_value::<AppInput>(json!({
                "action": "release", "app": "demo",
            }))
            .is_err()
        );
        let zone: ZoneInput = serde_json::from_value(json!({"action": "list"})).unwrap();
        assert!(matches!(zone, ZoneInput::List {}));
        assert!(
            serde_json::from_value::<ZoneInput>(json!({
                "action": "list", "label": "unused",
            }))
            .is_err()
        );
    }
}