feat: Implement SEP-2663 Tasks Extension (#1020)

* feat!: implement SEP-2663 Tasks extension, removing the experimental 2025-11-25 tasks design

Reshape tasks from the experimental SEP-1319/1686 core-protocol feature into
the official io.modelcontextprotocol/tasks extension (SEP-2663):

Model:
- Re-model Task (statusMessage, ttlMs nullable, pollIntervalMs) and add
  DetailedTask with status-discriminated payloads (inputRequests/result/error
  inlined per spec)
- CreateTaskResult now flattens Task with resultType: "task";
  add ResultType::TASK and CallToolResponse::Task
- Add tasks/update (UpdateTaskParams with MRTR InputResponses); tasks/get and
  tasks/cancel reworked; remove tasks/list, tasks/result
- notifications/tasks now carries a full DetailedTask; removed from client
  notifications (SEP-2260)

Capabilities:
- Remove core TasksCapability et al; tasks are declared via the extensions
  map (enable_tasks() builders, supports_tasks() accessors)
- Remove tool-level execution.taskSupport and the _meta.task /
  TaskMetadata / with_task() opt-in: task creation is server-directed and
  gated on the per-request client capability

Runtime:
- Replace OperationProcessor with TaskManager: durable-before-response task
  creation, input_required round-trips via tasks/update, cooperative
  cancellation, TTL expiry
- Client peer helpers get_task/update_task/cancel_task
- Emit Mcp-Name routing header from params.taskId for tasks/* methods
  (SEP-2243/2663)

Macros:
- Remove #[task_handler] and the tool execution() attribute

Tests/examples/docs updated; schema snapshots regenerated.

BREAKING CHANGE: the 2025-11-25 experimental tasks API is removed without a
compatibility shim. Clients that do not declare the tasks extension always
receive synchronous results.

* feat: gate tasks/* methods on the client tasks-extension capability (SEP-2663)

When the server advertises io.modelcontextprotocol/tasks but the client did
not declare it (per-request _meta clientCapabilities, or initialize-time
capabilities in session mode), tasks/get, tasks/update, and tasks/cancel now
return -32021 Missing Required Client Capability with the required extension
in the error data, instead of falling through to the handler's -32601
default. Servers that do not advertise the extension keep returning -32601.

Also add regression tests confirming that unknown taskIds yield -32602 and
that a legacy 2025-11-25 'task' param on tools/call is silently ignored.

* feat: pass SEP-2663 Tasks extension conformance suite

Conformance fixtures (conformance/src/bin/server.rs):
- Add the required fixture tools: greet (sync-only), slow_compute,
  failing_job (task support: required), protocol_error_job, confirm_delete,
  multi_input, and test_tool_with_task (MRTR -> task escalation), all backed
  by TaskManager with server-directed task creation gated on the client's
  tasks-extension capability
- Advertise io.modelcontextprotocol/tasks in server capabilities and wire
  get_task/update_task/cancel_task handlers
- Task-required tools reject with -32021 when the client did not declare the
  extension

SDK wire-shape fixes surfaced by the suite:
- Add resultType: "complete" to GetTaskResult and introduce TaskAckResult
  so tasks/update and tasks/cancel acks carry the SEP-2322 discriminator
  (spec: every non-CreateTaskResult response on the tasks surface is
  resultType complete); dispatch now returns ServerResult::task_ack
- CreateTaskResult gets a strict deserializer requiring resultType: "task"
  so it does not shadow task-shaped results in untagged unions
- Client update_task/cancel_task accept both TaskAckResult and EmptyResult

All 9 runnable Tasks extension server scenarios now pass (35/35 checks;
tasks-status-notifications remains upstream-skipped), so the corresponding
entries are removed from conformance/expected-failures-extensions.yaml.
2025-11-25 server suite (40/40), 2026-07-28 server suite (114/114), draft
client suite, and extensions client suite all pass their baselines.

* fix: address PR 1020 review feedback on DetailedTask schema and cooperative cancel

- DetailedTask's JsonSchema now derives from the actual flattened wire shape
  (DetailedTaskWire: base Task + optional inputRequests/result/error) instead
  of approximating with the base Task schema, so generated schemas for
  GetTaskResult and notifications/tasks document the status-specific payload
  fields. Golden message schemas regenerated.

- TaskManager::cancel_task no longer aborts the underlying future. It records
  the observable cancelled state and acks immediately (spec's eventually
  consistent semantics), but lets the operation keep running so it can observe
  is_cancel_requested() or the error from a woken request_input() and perform
  cleanup; any late result is discarded. New unit tests cover both the
  cooperative-cleanup path and waking parked input requests.

* fix: make tasks/cancel truly cooperative per SEP-2663 (FEEDBACK_2)

- TaskManager::cancel_task no longer forces terminal 'cancelled'. It records
  the cancellation intent, acks immediately, and wakes parked request_input
  awaits, but the operation decides its own terminal state: a post-cancel
  error settles as 'cancelled', while an operation that finishes its work
  settles as 'completed' — per the spec, 'the task may still reach a
  non-cancelled terminal status'.
- Add TaskContext::cancelled(), a watch-based await for use with
  tokio::select! as the cooperative cancellation exit path.
- Correct the unsupported-notification method string from
  'notifications/tasks/status' to 'notifications/tasks' and document that
  task status notifications are not yet routable through subscriptions/listen
  (SubscriptionFilter has no taskIds field; upstream check still skipped).
- Update conformance slow_compute fixture, task_demo example, and tests to
  honor cancellation via ctx.cancelled(); lifecycle conformance still 8/8
  (all 9 scenarios remain green, 35/35 checks).

* fix: sweep and evict expired tasks from TaskManager (FEEDBACK_3)

TTL handling previously only ran from get_task and only flipped overdue
non-terminal tasks to 'failed', never removing entries — an unbounded leak
for long-lived servers, and it made ttl_ms: None = 'unlimited retention'
meaningless since everything was retained forever.

- Rename expire_overdue to sweep_expired and run it from every entry point
  (spawn, get_task, update_task, cancel_task).
- Track terminal_at on each entry; terminal tasks are evicted after being
  retained for one further ttl_ms window past their terminal transition, so
  well-behaved pollers can observe the final state before late tasks/get
  calls return -32602 (spec: servers may delete expired tasks at any time,
  and returning task-not-found for purged tasks is compliant behavior).
- ttl_ms: None entries are never evicted (spec: unlimited retention);
  document the retention model on TaskManager, including that there is no
  background sweeper.
- New tests: retention-window eviction, sweep of abandoned tasks via other
  entry points, unlimited-TTL retention, and error-code assertions
  (-32602) for unknown ids across get/update/cancel.

Reviewed the second feedback item (dedicated task-not-found error code)
against SEP-2663 §Protocol Errors and it is incorrect: the SEP explicitly
specifies -32602 (Invalid params) for invalid or nonexistent taskIds, which
is what unknown_task already returns. Kept -32602; strengthened tests to
assert the code.

* fix: address Copilot review feedback on PR #1020

- TaskManager: drop the JoinHandle as soon as the operation settles instead
  of retaining it for the whole retention window, and only store it at spawn
  time if the task is still non-terminal (avoids keeping a completed handle
  that the completion path could never clear).
- Use RequestContext::client_capabilities() (which applies the initialize-time
  fallback for session peers) instead of raw context.meta.client_capabilities()
  in the task_demo example, the README snippet, and the test server — the
  meta-only form would wrongly treat session-declared tasks clients as
  unsupported.

All 9 Tasks extension conformance scenarios remain green (35/35 checks).

* fix: enforce SEP-2663 task-result gating in tools/call dispatch

A handler could return CallToolResponse::Task without checking whether the
request declared the io.modelcontextprotocol/tasks extension, sending a
CreateTaskResult to a client that cannot parse it. The SDK dispatch now
rejects that case with -32021 Missing Required Client Capability before the
response leaves the server, using RequestContext::client_capabilities()
(per-request _meta with initialize-time fallback).

Adds a regression test with a deliberately misbehaving handler that always
materializes a task; all Tasks extension conformance scenarios remain green
(35/35 checks).

* fix: align TTL boundary comparisons in sweep_expired

Copilot review: ttlMs: 0 never expired immediately because phase 1 used a
strict 'elapsed > ttl_ms' comparison, and phase 2 retained terminal tasks
at exactly the TTL boundary ('elapsed <= ttl_ms'). Treat elapsed >= ttl_ms
as expired in phase 1 and evict when elapsed >= ttl_ms in phase 2, so both
phases agree at the boundary and ttlMs: 0 expires/evicts on the first sweep.

* fix: strict TaskAckResult deserializer and TASK_REQUIRED_TOOLS consistency

- TaskAckResult carried only resultType (+ optional _meta) with a derived
  Deserialize, so inside the untagged ServerResult union it greedily matched
  any result object containing a resultType key, shadowing CustomResult and
  losing data (verified with a probe). Replace with a strict deserializer:
  deny_unknown_fields and require resultType == "complete". Regression
  tests cover both the non-matching shapes and the genuine ack shape.

- Conformance fixtures: confirm_delete and multi_input rejected non-tasks
  clients inline, contradicting the TASK_REQUIRED_TOOLS doc/constant. Move
  them into TASK_REQUIRED_TOOLS (they park on in-task elicitation and have
  no synchronous fallback) so the upfront -32021 gate is the single source
  of truth, and drop the now-unreachable inline checks.

All 9 Tasks extension conformance scenarios remain green (35/35 checks).

* fix: let the operation decide its terminal state via TaskExit

After tasks/cancel, any operation error was coerced to terminal
'cancelled', masking real failures (e.g. an unrelated error landing just
after a late cancel request) and contradicting the documented 'operation
decides its own terminal state' contract.

Change TaskFuture's error type from McpError to a new TaskExit enum:

- TaskExit::Cancelled — an explicit cooperative-cancellation exit;
  settles as terminal 'cancelled'.
- TaskExit::Error(McpError) — a real failure; settles as terminal
  'failed' with the error inlined, even after tasks/cancel was received.

From<McpError> for TaskExit keeps '?' ergonomic in task bodies, and
request_input() now returns TaskExit directly (its wake-on-cancel path
yields TaskExit::Cancelled), so parked operations that propagate it with
'?' settle as 'cancelled' automatically.

Update the conformance fixtures, task_demo example, and tests; add a
regression test asserting a post-cancel unrelated error settles as
'failed' with its error payload preserved.

All 9 Tasks extension conformance scenarios remain green (35/35 checks).

* fix: allow TaskExit enum to be exhaustive

* fix: close spawn/shutdown race, sweep in running_task_count, clarify TTL retention docs

Addresses branch-review findings:

- spawn() raced with shutdown(): if shutdown drained the task map between
  the entry insert and the JoinHandle store, the handle was dropped and the
  operation kept running detached. If the entry is gone at store time, the
  handle is now aborted instead.
- running_task_count() now runs the TTL sweep like every other entry point,
  so it no longer reports overdue tasks as running (matching the documented
  sweep-on-every-entry-point behavior). Regression test added.
- Document that terminal-task retention intentionally extends one ttl_ms
  window past the terminal transition (observation grace period) beyond the
  creation-based lifetime ttlMs advertises on the wire — compliant since
  SEP-2663 allows deleting expired tasks at any time after the TTL.
This commit is contained in:
Jack Amadeo 2026-07-22 14:16:52 -04:00 • committed by GitHub
commit 07abfdfd99
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 2950 additions and 3236 deletions

View file

@ -7,7 +7,6 @@ mod common;
mod prompt;
mod prompt_handler;
mod prompt_router;
mod task_handler;
mod tool;
mod tool_handler;
mod tool_router;
@ -100,7 +99,7 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> TokenStream {
/// impl MyToolHandler {
/// #[tool]
/// fn my_tool_a() {
///
///
/// }
/// }
/// }
@ -110,7 +109,7 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> TokenStream {
/// impl MyToolHandler {
/// #[tool]
/// fn my_tool_b() {
///
///
/// }
/// }
/// }
@ -299,17 +298,3 @@ pub fn prompt_handler(attr: TokenStream, input: TokenStream) -> TokenStream {
.unwrap_or_else(|err| err.to_compile_error())
.into()
}
/// # task_handler
///
/// Generates basic task-handling methods (`enqueue_task` and `list_tasks`) for a server handler
/// using a shared \[`OperationProcessor`\]. The default processor expression assumes a
/// `self.processor` field holding an `Arc<Mutex<OperationProcessor>>`, but it can be customized
/// via `#[task_handler(processor = ...)]`. Because the macro captures `self` inside spawned
/// futures, the handler type must implement [`Clone`].
#[proc_macro_attribute]
pub fn task_handler(attr: TokenStream, input: TokenStream) -> TokenStream {
task_handler::task_handler(attr.into(), input.into())
.unwrap_or_else(|err| err.to_compile_error())
.into()
}

View file

@ -1,286 +0,0 @@
use darling::{FromMeta, ast::NestedMeta};
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use syn::{Expr, ImplItem, ItemImpl};
use crate::common::{has_method, has_sibling_handler};
#[derive(FromMeta)]
#[darling(default)]
struct TaskHandlerAttribute {
processor: Expr,
}
impl Default for TaskHandlerAttribute {
fn default() -> Self {
Self {
processor: syn::parse2(quote! { self.processor }).expect("default processor expr"),
}
}
}
pub fn task_handler(attr: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
let attr_args = NestedMeta::parse_meta_list(attr)?;
let TaskHandlerAttribute { processor } = TaskHandlerAttribute::from_list(&attr_args)?;
let mut item_impl = syn::parse2::<ItemImpl>(input)?;
if !has_method("list_tasks", &item_impl) {
let list_fn = quote! {
async fn list_tasks(
&self,
_request: Option<rmcp::model::PaginatedRequestParams>,
_: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::ListTasksResult, McpError> {
let running_ids = (#processor).lock().await.list_running();
let total = running_ids.len() as u64;
let tasks = running_ids
.into_iter()
.map(|task_id| {
let timestamp = rmcp::task_manager::current_timestamp();
rmcp::model::Task::new(
task_id,
rmcp::model::TaskStatus::Working,
timestamp.clone(),
timestamp,
)
})
.collect::<Vec<_>>();
Ok(rmcp::model::ListTasksResult::new(tasks))
}
};
item_impl.items.push(syn::parse2::<ImplItem>(list_fn)?);
}
if !has_method("enqueue_task", &item_impl) {
let enqueue_fn = quote! {
async fn enqueue_task(
&self,
request: rmcp::model::CallToolRequestParams,
context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::CreateTaskResult, McpError> {
use rmcp::task_manager::{
current_timestamp, OperationDescriptor, OperationMessage, OperationResultTransport,
ToolCallTaskResult,
};
let task_id = context.id.to_string();
let operation_name = request.name.to_string();
let future_request = request.clone();
let future_context = context.clone();
let server = self.clone();
let descriptor = OperationDescriptor::new(task_id.clone(), operation_name)
.with_context(context)
.with_client_request(rmcp::model::ClientRequest::CallToolRequest(
rmcp::model::Request::new(request),
));
let task_result_id = task_id.clone();
let future = Box::pin(async move {
let result = server
.call_tool(future_request, future_context)
.await
.and_then(|response| match response {
rmcp::model::CallToolResponse::Complete(result) => Ok(result),
_ => Err(rmcp::ErrorData::internal_error(
"input_required is not supported for task-based tool calls",
None,
)),
});
Ok(
Box::new(ToolCallTaskResult::new(task_result_id, result))
as Box<dyn OperationResultTransport>,
)
});
(#processor)
.lock()
.await
.submit_operation(OperationMessage::new(descriptor, future))
.map_err(|err| rmcp::ErrorData::internal_error(
format!("failed to enqueue task: {err}"),
None,
))?;
let timestamp = current_timestamp();
let task = rmcp::model::Task::new(
task_id,
rmcp::model::TaskStatus::Working,
timestamp.clone(),
timestamp,
).with_status_message("Task accepted");
Ok(rmcp::model::CreateTaskResult::new(task))
}
};
item_impl.items.push(syn::parse2::<ImplItem>(enqueue_fn)?);
}
if !has_method("get_task_info", &item_impl) {
let get_info_fn = quote! {
async fn get_task_info(
&self,
request: rmcp::model::GetTaskParams,
_context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::GetTaskResult, McpError> {
use rmcp::task_manager::current_timestamp;
let task_id = request.task_id.clone();
let mut processor = (#processor).lock().await;
// Check completed results first
let completed = processor.peek_completed().iter().rev().find(|r| r.descriptor.operation_id == task_id);
if let Some(completed_result) = completed {
// Determine Finished vs Failed
let status = match &completed_result.result {
Ok(boxed) => {
if let Some(tool) = boxed.as_any().downcast_ref::<rmcp::task_manager::ToolCallTaskResult>() {
match &tool.result {
Ok(_) => rmcp::model::TaskStatus::Completed,
Err(_) => rmcp::model::TaskStatus::Failed,
}
} else {
rmcp::model::TaskStatus::Completed
}
}
Err(_) => rmcp::model::TaskStatus::Failed,
};
let timestamp = current_timestamp();
let mut task = rmcp::model::Task::new(
task_id,
status,
timestamp.clone(),
timestamp,
);
if let Some(ttl) = completed_result.descriptor.ttl {
task = task.with_ttl(ttl);
}
return Ok(rmcp::model::GetTaskResult::new(task));
}
// If not completed, check running
let running = processor.list_running();
if running.into_iter().any(|id| id == task_id) {
let timestamp = current_timestamp();
let task = rmcp::model::Task::new(
task_id,
rmcp::model::TaskStatus::Working,
timestamp.clone(),
timestamp,
);
return Ok(rmcp::model::GetTaskResult::new(task));
}
Err(McpError::resource_not_found(format!("task not found: {}", task_id), None))
}
};
item_impl.items.push(syn::parse2::<ImplItem>(get_info_fn)?);
}
if !has_method("get_task_result", &item_impl) {
let get_result_fn = quote! {
async fn get_task_result(
&self,
request: rmcp::model::GetTaskPayloadParams,
_context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::GetTaskPayloadResult, McpError> {
use std::time::Duration;
let task_id = request.task_id.clone();
loop {
// Scope the lock so we can await outside if needed
{
let mut processor = (#processor).lock().await;
if let Some(task_result) = processor.take_completed_result(&task_id) {
match task_result.result {
Ok(boxed) => {
if let Some(tool) = boxed.as_any().downcast_ref::<rmcp::task_manager::ToolCallTaskResult>() {
match &tool.result {
Ok(call_tool) => {
let value = ::rmcp::serde_json::to_value(call_tool).unwrap_or_default();
return Ok(rmcp::model::GetTaskPayloadResult::new(value));
}
Err(err) => return Err(McpError::internal_error(
format!("task failed: {}", err),
None,
)),
}
} else {
return Err(McpError::internal_error("unsupported task result transport", None));
}
}
Err(err) => return Err(McpError::internal_error(
format!("task execution error: {}", err),
None,
)),
}
}
// Not completed yet: if not running, return not found
let running = processor.list_running();
if !running.iter().any(|id| id == &task_id) {
return Err(McpError::resource_not_found(format!("task not found: {}", task_id), None));
}
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
};
item_impl
.items
.push(syn::parse2::<ImplItem>(get_result_fn)?);
}
if !has_method("cancel_task", &item_impl) {
let cancel_fn = quote! {
async fn cancel_task(
&self,
request: rmcp::model::CancelTaskParams,
_context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::CancelTaskResult, McpError> {
use rmcp::task_manager::current_timestamp;
let task_id = request.task_id;
let mut processor = (#processor).lock().await;
if processor.cancel_task(&task_id) {
let timestamp = current_timestamp();
let task = rmcp::model::Task::new(
task_id,
rmcp::model::TaskStatus::Cancelled,
timestamp.clone(),
timestamp,
);
return Ok(rmcp::model::CancelTaskResult::new(task));
}
// If already completed, signal it's not cancellable
let exists_completed = processor.peek_completed().iter().any(|r| r.descriptor.operation_id == task_id);
if exists_completed {
return Err(McpError::invalid_request(format!("task already completed: {}", task_id), None));
}
Err(McpError::resource_not_found(format!("task not found: {}", task_id), None))
}
};
item_impl.items.push(syn::parse2::<ImplItem>(cancel_fn)?);
}
// Auto-generate get_info() if not already provided and no sibling tool/prompt handler
// will generate it (they take priority since they run as outer attributes).
if !has_method("get_info", &item_impl)
&& !has_sibling_handler(&item_impl, "tool_handler")
&& !has_sibling_handler(&item_impl, "prompt_handler")
{
let get_info_fn = crate::tool_handler::build_get_info(
&item_impl,
None,
None,
None,
crate::tool_handler::CallerCapability::Tasks,
)?;
item_impl.items.push(get_info_fn);
}
Ok(item_impl.into_token_stream())
}

View file

@ -75,8 +75,6 @@ pub struct ToolAttribute {
pub output_schema: Option<Expr>,
/// Optional additional tool information.
pub annotations: Option<ToolAnnotationsAttribute>,
/// Execution-related configuration including task support.
pub execution: Option<ToolExecutionAttribute>,
/// Optional icons for the tool
pub icons: Option<Expr>,
/// Optional metadata for the tool
@ -86,13 +84,6 @@ pub struct ToolAttribute {
pub local: bool,
}
#[derive(FromMeta, Debug, Default)]
#[darling(default)]
pub struct ToolExecutionAttribute {
/// Task support mode: "forbidden", "optional", or "required"
pub task_support: Option<String>,
}
pub struct ResolvedToolAttribute {
pub name: String,
pub title: Option<String>,
@ -100,7 +91,6 @@ pub struct ResolvedToolAttribute {
pub input_schema: Expr,
pub output_schema: Option<Expr>,
pub annotations: Option<Expr>,
pub execution: Option<Expr>,
pub icons: Option<Expr>,
pub meta: Option<Expr>,
}
@ -114,7 +104,6 @@ impl ResolvedToolAttribute {
input_schema,
output_schema,
annotations,
execution,
icons,
meta,
} = self;
@ -132,9 +121,6 @@ impl ResolvedToolAttribute {
let annotations_call = annotations
.map(|a| quote! { .with_annotations(#a) })
.unwrap_or_default();
let execution_call = execution
.map(|e| quote! { .with_execution(#e) })
.unwrap_or_default();
let icons_call = icons
.map(|i| quote! { .with_icons(#i) })
.unwrap_or_default();
@ -152,7 +138,6 @@ impl ResolvedToolAttribute {
#title_call
#output_schema_call
#annotations_call
#execution_call
#icons_call
#meta_call
}
@ -264,38 +249,6 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
} else {
None
};
let execution_expr = if let Some(execution) = attribute.execution {
let ToolExecutionAttribute { task_support } = execution;
let task_support_expr = if let Some(ts) = task_support {
let ts_ident = match ts.as_str() {
"forbidden" => quote! { rmcp::model::TaskSupport::Forbidden },
"optional" => quote! { rmcp::model::TaskSupport::Optional },
"required" => quote! { rmcp::model::TaskSupport::Required },
_ => {
return Err(syn::Error::new(
Span::call_site(),
format!(
"Invalid task_support value '{}'. Expected 'forbidden', 'optional', or 'required'",
ts
),
));
}
};
quote! { Some(#ts_ident) }
} else {
quote! { None }
};
let token_stream = quote! {
rmcp::model::ToolExecution::from_raw(
#task_support_expr,
)
};
Some(syn::parse2::<Expr>(token_stream)?)
} else {
None
};
// Handle output_schema - either explicit or generated from return type
let output_schema_expr = attribute.output_schema.or_else(|| {
// Try to generate schema from return type
@ -319,7 +272,6 @@ pub fn tool(attr: TokenStream, input: TokenStream) -> syn::Result<TokenStream> {
input_schema: input_schema_expr,
output_schema: output_schema_expr,
annotations: annotations_expr,
execution: execution_expr,
title: attribute.title,
icons: attribute.icons,
meta: attribute.meta,

View file

@ -110,13 +110,12 @@ pub fn tool_handler(attr: TokenStream, input: TokenStream) -> syn::Result<TokenS
pub(crate) enum CallerCapability {
Tools,
Prompts,
Tasks,
}
/// Build a `get_info()` method that returns `ServerInfo` with the appropriate capabilities.
///
/// The caller declares its own capability via `caller`. Sibling handler attributes
/// (`prompt_handler`, `task_handler`, `tool_handler`) are detected automatically
/// (`prompt_handler`, `tool_handler`) are detected automatically
/// and their capabilities are included.
pub(crate) fn build_get_info(
item_impl: &ItemImpl,
@ -129,8 +128,6 @@ pub(crate) fn build_get_info(
caller == CallerCapability::Tools || has_sibling_handler(item_impl, "tool_handler");
let has_prompts =
caller == CallerCapability::Prompts || has_sibling_handler(item_impl, "prompt_handler");
let has_tasks =
caller == CallerCapability::Tasks || has_sibling_handler(item_impl, "task_handler");
let mut capability_calls = Vec::new();
if has_tools {
@ -139,10 +136,6 @@ pub(crate) fn build_get_info(
if has_prompts {
capability_calls.push(quote! { .enable_prompts() });
}
if has_tasks {
capability_calls.push(quote! { .enable_tasks() });
}
let server_info_expr = match (name, version) {
(Some(n), Some(v)) => quote! { rmcp::model::Implementation::new(#n, #v) },
(Some(n), None) => {