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,
#[serde(default, deserialize_with = "deserialize_duration")]
#[schemars(with = "Option<String>", regex(pattern = "^[0-9]*[1-9][0-9]*[smhd]$"))]
duration: Option<SignedDuration>,
#[serde(deserialize_with = "deserialize_pid", default)]
pid: Option<NonZeroU32>,
#[serde(deserialize_with = "deserialize_bind", default)]
bind: Option<IpAddr>,
#[serde(deserialize_with = "deserialize_group", default)]
group: Option<Vec<String>>,
#[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>,
#[serde(default, deserialize_with = "deserialize_present")]
#[schemars(with = "String")]
group: Option<String>,
#[serde(default, deserialize_with = "deserialize_duration")]
#[schemars(with = "Option<String>", regex(pattern = "^[0-9]*[1-9][0-9]*[smhd]$"))]
duration: Option<SignedDuration>,
#[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>,
#[serde(default, deserialize_with = "deserialize_target_leased_at")]
#[schemars(with = "String")]
leased_at: Option<OffsetDateTime>,
#[serde(default, deserialize_with = "deserialize_present")]
#[schemars(with = "String")]
group: Option<String>,
#[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,
#[serde(default)]
force_shared: bool,
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>>,
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,
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,
#[serde(default, deserialize_with = "edit::deserialize_nullable_string")]
#[schemars(with = "Option<String>")]
container: Option<Option<String>>,
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,
tag: String,
purpose: Option<String>,
#[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,
ports: Vec<String>,
reason: Option<String>,
#[serde(default)]
disabled: bool,
},
List {},
Enable {
label: String,
},
Disable {
label: String,
},
Edit {
label: String,
tag: String,
#[serde(default, deserialize_with = "edit::deserialize_nullable_string")]
#[schemars(with = "Option<String>")]
reason: Option<Option<String>>,
ports: Option<Vec<String>>,
},
Remove {
label: String,
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,
components: Vec<String>,
#[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,
tag: Option<String>,
},
Edit {
app: String,
component: String,
tag: String,
#[serde(deserialize_with = "deserialize_edit_fields")]
#[schemars(with = "EditFields")]
changes: JsonObject<EditFields>,
},
Release {
app: String,
confirm: String,
tag: Option<String>,
},
}
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)
}
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))?;
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> {
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> {
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()
);
}
}