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:
parent
ac9c637d04
commit
07abfdfd99
6 changed files with 2950 additions and 3236 deletions
|
|
@ -72,130 +72,6 @@ pub struct RootsCapabilities {
|
|||
pub list_changed: Option<bool>,
|
||||
}
|
||||
|
||||
/// Task capabilities shared by client and server.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct TasksCapability {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub requests: Option<TaskRequestsCapability>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub list: Option<JsonObject>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub cancel: Option<JsonObject>,
|
||||
}
|
||||
|
||||
/// Request types that support task-augmented execution.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct TaskRequestsCapability {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub sampling: Option<SamplingTaskCapability>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub elicitation: Option<ElicitationTaskCapability>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tools: Option<ToolsTaskCapability>,
|
||||
}
|
||||
|
||||
/// Sampling task capability. Deprecated by SEP-2577; remains functional and
|
||||
/// will be removed in a future release.
|
||||
/// See <https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577>.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct SamplingTaskCapability {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub create_message: Option<JsonObject>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct ElicitationTaskCapability {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub create: Option<JsonObject>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct ToolsTaskCapability {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub call: Option<JsonObject>,
|
||||
}
|
||||
|
||||
impl TasksCapability {
|
||||
/// Default client tasks capability with sampling and elicitation support.
|
||||
pub fn client_default() -> Self {
|
||||
Self {
|
||||
list: Some(JsonObject::new()),
|
||||
cancel: Some(JsonObject::new()),
|
||||
requests: Some(TaskRequestsCapability {
|
||||
sampling: Some(SamplingTaskCapability {
|
||||
create_message: Some(JsonObject::new()),
|
||||
}),
|
||||
elicitation: Some(ElicitationTaskCapability {
|
||||
create: Some(JsonObject::new()),
|
||||
}),
|
||||
tools: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Default server tasks capability with tools/call support.
|
||||
pub fn server_default() -> Self {
|
||||
Self {
|
||||
list: Some(JsonObject::new()),
|
||||
cancel: Some(JsonObject::new()),
|
||||
requests: Some(TaskRequestsCapability {
|
||||
sampling: None,
|
||||
elicitation: None,
|
||||
tools: Some(ToolsTaskCapability {
|
||||
call: Some(JsonObject::new()),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn supports_list(&self) -> bool {
|
||||
self.list.is_some()
|
||||
}
|
||||
|
||||
pub fn supports_cancel(&self) -> bool {
|
||||
self.cancel.is_some()
|
||||
}
|
||||
|
||||
pub fn supports_tools_call(&self) -> bool {
|
||||
self.requests
|
||||
.as_ref()
|
||||
.and_then(|r| r.tools.as_ref())
|
||||
.and_then(|t| t.call.as_ref())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
pub fn supports_sampling_create_message(&self) -> bool {
|
||||
self.requests
|
||||
.as_ref()
|
||||
.and_then(|r| r.sampling.as_ref())
|
||||
.and_then(|s| s.create_message.as_ref())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
pub fn supports_elicitation_create(&self) -> bool {
|
||||
self.requests
|
||||
.as_ref()
|
||||
.and_then(|r| r.elicitation.as_ref())
|
||||
.and_then(|e| e.create.as_ref())
|
||||
.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// Capability for handling elicitation requests from servers.
|
||||
/// Elicitation allows servers to request interactive input from users during tool execution.
|
||||
/// This capability indicates that a client can handle elicitation requests and present
|
||||
|
|
@ -316,8 +192,16 @@ pub struct ClientCapabilities {
|
|||
/// Capability to handle elicitation requests from servers for interactive user input
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub elicitation: Option<ElicitationCapability>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tasks: Option<TasksCapability>,
|
||||
}
|
||||
|
||||
impl ClientCapabilities {
|
||||
/// Returns `true` if the `io.modelcontextprotocol/tasks` extension
|
||||
/// (SEP-2663) is declared in [`Self::extensions`].
|
||||
pub fn supports_tasks(&self) -> bool {
|
||||
self.extensions
|
||||
.as_ref()
|
||||
.is_some_and(|e| e.contains_key(super::TASKS_EXTENSION_ID))
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
|
|
@ -356,8 +240,16 @@ pub struct ServerCapabilities {
|
|||
pub resources: Option<ResourcesCapability>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tools: Option<ToolsCapability>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tasks: Option<TasksCapability>,
|
||||
}
|
||||
|
||||
impl ServerCapabilities {
|
||||
/// Returns `true` if the `io.modelcontextprotocol/tasks` extension
|
||||
/// (SEP-2663) is declared in [`Self::extensions`].
|
||||
pub fn supports_tasks(&self) -> bool {
|
||||
self.extensions
|
||||
.as_ref()
|
||||
.is_some_and(|e| e.contains_key(super::TASKS_EXTENSION_ID))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
|
|
@ -484,20 +376,12 @@ builder! {
|
|||
prompts: PromptsCapability,
|
||||
resources: ResourcesCapability,
|
||||
tools: ToolsCapability,
|
||||
tasks: TasksCapability
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
impl<
|
||||
const E: bool,
|
||||
const EXT: bool,
|
||||
const L: bool,
|
||||
const C: bool,
|
||||
const P: bool,
|
||||
const R: bool,
|
||||
const TASKS: bool,
|
||||
> ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, P, R, true, TASKS>>
|
||||
impl<const E: bool, const EXT: bool, const L: bool, const C: bool, const P: bool, const R: bool>
|
||||
ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, P, R, true>>
|
||||
{
|
||||
pub fn enable_tool_list_changed(mut self) -> Self {
|
||||
if let Some(c) = self.tools.as_mut() {
|
||||
|
|
@ -508,15 +392,8 @@ impl<
|
|||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
impl<
|
||||
const E: bool,
|
||||
const EXT: bool,
|
||||
const L: bool,
|
||||
const C: bool,
|
||||
const R: bool,
|
||||
const T: bool,
|
||||
const TASKS: bool,
|
||||
> ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, true, R, T, TASKS>>
|
||||
impl<const E: bool, const EXT: bool, const L: bool, const C: bool, const R: bool, const T: bool>
|
||||
ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, true, R, T>>
|
||||
{
|
||||
pub fn enable_prompts_list_changed(mut self) -> Self {
|
||||
if let Some(c) = self.prompts.as_mut() {
|
||||
|
|
@ -527,15 +404,8 @@ impl<
|
|||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
impl<
|
||||
const E: bool,
|
||||
const EXT: bool,
|
||||
const L: bool,
|
||||
const C: bool,
|
||||
const P: bool,
|
||||
const T: bool,
|
||||
const TASKS: bool,
|
||||
> ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, P, true, T, TASKS>>
|
||||
impl<const E: bool, const EXT: bool, const L: bool, const C: bool, const P: bool, const T: bool>
|
||||
ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, P, true, T>>
|
||||
{
|
||||
pub fn enable_resources_list_changed(mut self) -> Self {
|
||||
if let Some(c) = self.resources.as_mut() {
|
||||
|
|
@ -552,6 +422,18 @@ impl<
|
|||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
impl<S> ServerCapabilitiesBuilder<S> {
|
||||
/// Declare support for the `io.modelcontextprotocol/tasks` extension
|
||||
/// (SEP-2663) in the `extensions` capability map.
|
||||
pub fn enable_tasks(mut self) -> Self {
|
||||
self.extensions
|
||||
.get_or_insert_with(ExtensionCapabilities::new)
|
||||
.insert(super::TASKS_EXTENSION_ID.to_string(), JsonObject::new());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
builder! {
|
||||
ClientCapabilities{
|
||||
|
|
@ -568,13 +450,24 @@ builder! {
|
|||
)]
|
||||
sampling: SamplingCapability,
|
||||
elicitation: ElicitationCapability,
|
||||
tasks: TasksCapability,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
impl<const E: bool, const EXT: bool, const S: bool, const EL: bool, const TASKS: bool>
|
||||
ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, true, S, EL, TASKS>>
|
||||
impl<S> ClientCapabilitiesBuilder<S> {
|
||||
/// Declare support for the `io.modelcontextprotocol/tasks` extension
|
||||
/// (SEP-2663) in the `extensions` capability map.
|
||||
pub fn enable_tasks(mut self) -> Self {
|
||||
self.extensions
|
||||
.get_or_insert_with(ExtensionCapabilities::new)
|
||||
.insert(super::TASKS_EXTENSION_ID.to_string(), JsonObject::new());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
impl<const E: bool, const EXT: bool, const S: bool, const EL: bool>
|
||||
ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, true, S, EL>>
|
||||
{
|
||||
#[deprecated(
|
||||
since = "1.8.0",
|
||||
|
|
@ -589,8 +482,8 @@ impl<const E: bool, const EXT: bool, const S: bool, const EL: bool, const TASKS:
|
|||
}
|
||||
|
||||
#[cfg(any(feature = "server", feature = "macros"))]
|
||||
impl<const E: bool, const EXT: bool, const R: bool, const EL: bool, const TASKS: bool>
|
||||
ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, R, true, EL, TASKS>>
|
||||
impl<const E: bool, const EXT: bool, const R: bool, const EL: bool>
|
||||
ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, R, true, EL>>
|
||||
{
|
||||
/// Enable tool calling in sampling requests
|
||||
#[deprecated(
|
||||
|
|
@ -618,8 +511,8 @@ impl<const E: bool, const EXT: bool, const R: bool, const EL: bool, const TASKS:
|
|||
}
|
||||
|
||||
#[cfg(all(feature = "elicitation", any(feature = "server", feature = "macros")))]
|
||||
impl<const E: bool, const EXT: bool, const R: bool, const S: bool, const TASKS: bool>
|
||||
ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, R, S, true, TASKS>>
|
||||
impl<const E: bool, const EXT: bool, const R: bool, const S: bool>
|
||||
ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, R, S, true>>
|
||||
{
|
||||
/// Enable JSON Schema validation for elicitation responses in form mode.
|
||||
/// When enabled, the client will validate user input against the requested_schema
|
||||
|
|
@ -679,68 +572,25 @@ mod test {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn test_task_capabilities_deserialization() {
|
||||
// Test deserializing from the MCP spec format
|
||||
let json = serde_json::json!({
|
||||
"list": {},
|
||||
"cancel": {},
|
||||
"requests": {
|
||||
"tools": { "call": {} }
|
||||
}
|
||||
});
|
||||
|
||||
let tasks: TasksCapability = serde_json::from_value(json).unwrap();
|
||||
assert!(tasks.list.is_some());
|
||||
assert!(tasks.cancel.is_some());
|
||||
assert!(tasks.requests.is_some());
|
||||
let requests = tasks.requests.unwrap();
|
||||
assert!(requests.tools.is_some());
|
||||
assert!(requests.tools.unwrap().call.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tasks_capability_client_default() {
|
||||
let tasks = TasksCapability::client_default();
|
||||
|
||||
// Verify structure
|
||||
assert!(tasks.supports_list());
|
||||
assert!(tasks.supports_cancel());
|
||||
assert!(tasks.supports_sampling_create_message());
|
||||
assert!(tasks.supports_elicitation_create());
|
||||
assert!(!tasks.supports_tools_call());
|
||||
|
||||
// Verify serialization matches expected format
|
||||
let json = serde_json::to_value(&tasks).unwrap();
|
||||
assert_eq!(json["list"], serde_json::json!({}));
|
||||
assert_eq!(json["cancel"], serde_json::json!({}));
|
||||
fn test_tasks_extension_capability() {
|
||||
// SEP-2663: tasks are declared via the extensions map.
|
||||
let capabilities = ClientCapabilities::builder().enable_tasks().build();
|
||||
assert!(capabilities.supports_tasks());
|
||||
let json = serde_json::to_value(&capabilities).unwrap();
|
||||
assert_eq!(
|
||||
json["requests"]["sampling"]["createMessage"],
|
||||
json["extensions"][crate::model::TASKS_EXTENSION_ID],
|
||||
serde_json::json!({})
|
||||
);
|
||||
|
||||
let server = ServerCapabilities::builder().enable_tasks().build();
|
||||
assert!(server.supports_tasks());
|
||||
let json = serde_json::to_value(&server).unwrap();
|
||||
assert_eq!(
|
||||
json["requests"]["elicitation"]["create"],
|
||||
json["extensions"][crate::model::TASKS_EXTENSION_ID],
|
||||
serde_json::json!({})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tasks_capability_server_default() {
|
||||
let tasks = TasksCapability::server_default();
|
||||
|
||||
// Verify structure
|
||||
assert!(tasks.supports_list());
|
||||
assert!(tasks.supports_cancel());
|
||||
assert!(tasks.supports_tools_call());
|
||||
assert!(!tasks.supports_sampling_create_message());
|
||||
assert!(!tasks.supports_elicitation_create());
|
||||
|
||||
// Verify serialization matches expected format
|
||||
let json = serde_json::to_value(&tasks).unwrap();
|
||||
assert_eq!(json["list"], serde_json::json!({}));
|
||||
assert_eq!(json["cancel"], serde_json::json!({}));
|
||||
assert_eq!(json["requests"]["tools"]["call"], serde_json::json!({}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(deprecated)]
|
||||
fn test_client_extensions_capability() {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use serde_json::Value;
|
|||
use super::{
|
||||
ClientCapabilities, ClientNotification, ClientRequest, CustomNotification, CustomRequest,
|
||||
Extensions, Implementation, JsonObject, JsonRpcMessage, LoggingLevel, ProgressToken,
|
||||
ProtocolVersion, RequestId, ServerNotification, ServerRequest, TaskMetadata,
|
||||
ProtocolVersion, RequestId, ServerNotification, ServerRequest,
|
||||
};
|
||||
|
||||
/// Access to the metadata carried by a message envelope's [`Extensions`].
|
||||
|
|
@ -94,21 +94,6 @@ pub trait RequestParamsMeta {
|
|||
}
|
||||
}
|
||||
|
||||
/// Trait for task-augmented request params that contain both `_meta` and `task` fields.
|
||||
///
|
||||
/// Per the MCP 2025-11-25 spec, certain requests (like `tools/call` and `sampling/createMessage`)
|
||||
/// can include a `task` field to signal that the caller wants task-augmented execution.
|
||||
pub trait TaskAugmentedRequestParamsMeta: RequestParamsMeta {
|
||||
/// Get a reference to the task field
|
||||
fn task(&self) -> Option<&TaskMetadata>;
|
||||
/// Get a mutable reference to the task field
|
||||
fn task_mut(&mut self) -> &mut Option<TaskMetadata>;
|
||||
/// Set the task field
|
||||
fn set_task(&mut self, task: TaskMetadata) {
|
||||
*self.task_mut() = Some(task);
|
||||
}
|
||||
}
|
||||
|
||||
impl GetExtensions for CustomNotification {
|
||||
fn extensions(&self) -> &Extensions {
|
||||
&self.extensions
|
||||
|
|
@ -204,8 +189,7 @@ variant_extension! {
|
|||
ListToolsRequest
|
||||
CustomRequest
|
||||
GetTaskRequest
|
||||
ListTasksRequest
|
||||
GetTaskPayloadRequest
|
||||
UpdateTaskRequest
|
||||
CancelTaskRequest
|
||||
}
|
||||
}
|
||||
|
|
@ -226,7 +210,6 @@ variant_extension! {
|
|||
ProgressNotification
|
||||
InitializedNotification
|
||||
RootsListChangedNotification
|
||||
TaskStatusNotification
|
||||
CustomNotification
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,8 +42,8 @@ use serde::{Deserialize, Serialize};
|
|||
use serde_json::Value;
|
||||
|
||||
use super::{
|
||||
CallToolResult, CreateMessageRequest, ElicitRequest, GetPromptResult, ListRootsRequest,
|
||||
MetaObject, ReadResourceResult, ResultType, ServerResult,
|
||||
CallToolResult, CreateMessageRequest, CreateTaskResult, ElicitRequest, GetPromptResult,
|
||||
ListRootsRequest, MetaObject, ReadResourceResult, ResultType, ServerResult,
|
||||
};
|
||||
|
||||
/// Default maximum number of MRTR rounds a high-level client call will drive.
|
||||
|
|
@ -72,6 +72,18 @@ pub enum InputRequest {
|
|||
ListRoots(ListRootsRequest),
|
||||
}
|
||||
|
||||
// Wire-level equality: two `InputRequest`s are equal if they serialize to the
|
||||
// same JSON. The wrapped request envelopes do not implement `PartialEq`
|
||||
// structurally (they carry `Extensions`).
|
||||
impl PartialEq for InputRequest {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (serde_json::to_value(self), serde_json::to_value(other)) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A map of server-initiated requests that the client must fulfill.
|
||||
///
|
||||
/// Keys are server-assigned string identifiers; values are request objects
|
||||
|
|
@ -95,6 +107,9 @@ pub enum CallToolResponse {
|
|||
Complete(CallToolResult),
|
||||
/// The server requires client-side input before the tool call can complete.
|
||||
InputRequired(InputRequiredResult),
|
||||
/// The server materialized a task for this call (SEP-2663 Tasks extension,
|
||||
/// `resultType: "task"`). The client polls `tasks/get` for the result.
|
||||
Task(CreateTaskResult),
|
||||
}
|
||||
|
||||
impl From<CallToolResult> for CallToolResponse {
|
||||
|
|
@ -114,10 +129,17 @@ impl From<CallToolResponse> for ServerResult {
|
|||
match response {
|
||||
CallToolResponse::Complete(result) => ServerResult::CallToolResult(result),
|
||||
CallToolResponse::InputRequired(result) => ServerResult::InputRequiredResult(result),
|
||||
CallToolResponse::Task(result) => ServerResult::CreateTaskResult(result),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CreateTaskResult> for CallToolResponse {
|
||||
fn from(result: CreateTaskResult) -> Self {
|
||||
Self::Task(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of a `prompts/get` request, including the MRTR intermediate result.
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
|
|
|
|||
|
|
@ -497,7 +497,6 @@ mod test {
|
|||
meta: Some(params_meta),
|
||||
name: "my_tool".into(),
|
||||
arguments: None,
|
||||
task: None,
|
||||
input_responses: None,
|
||||
request_state: None,
|
||||
},
|
||||
|
|
@ -537,7 +536,6 @@ mod test {
|
|||
meta: None,
|
||||
name: "my_tool".into(),
|
||||
arguments: None,
|
||||
task: None,
|
||||
input_responses: None,
|
||||
request_state: None,
|
||||
},
|
||||
|
|
@ -560,7 +558,6 @@ mod test {
|
|||
meta: Some(params_meta),
|
||||
name: "my_tool".into(),
|
||||
arguments: None,
|
||||
task: None,
|
||||
input_responses: None,
|
||||
request_state: None,
|
||||
},
|
||||
|
|
@ -580,7 +577,6 @@ mod test {
|
|||
meta: None,
|
||||
name: "my_tool".into(),
|
||||
arguments: None,
|
||||
task: None,
|
||||
input_responses: None,
|
||||
request_state: None,
|
||||
},
|
||||
|
|
@ -612,7 +608,6 @@ mod test {
|
|||
meta: Some(params_meta),
|
||||
name: "my_tool".into(),
|
||||
arguments: None,
|
||||
task: None,
|
||||
input_responses: None,
|
||||
request_state: None,
|
||||
},
|
||||
|
|
@ -638,7 +633,6 @@ mod test {
|
|||
meta: None,
|
||||
name: "my_tool".into(),
|
||||
arguments: Some(serde_json::Map::from_iter([("x".to_string(), json!(1))])),
|
||||
task: None,
|
||||
input_responses: None,
|
||||
request_state: None,
|
||||
},
|
||||
|
|
@ -798,7 +792,6 @@ mod test {
|
|||
meta: None,
|
||||
name: "my_tool".into(),
|
||||
arguments: None,
|
||||
task: None,
|
||||
input_responses: None,
|
||||
request_state: None,
|
||||
},
|
||||
|
|
@ -826,7 +819,6 @@ mod test {
|
|||
meta: None,
|
||||
name: "my_tool".into(),
|
||||
arguments: None,
|
||||
task: None,
|
||||
input_responses: None,
|
||||
request_state: None,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,114 +1,90 @@
|
|||
//! Task types for the MCP Tasks extension (SEP-2663).
|
||||
//!
|
||||
//! Tasks are defined by the official `io.modelcontextprotocol/tasks` extension.
|
||||
//! A server may respond to a supported request (currently `tools/call`) with a
|
||||
//! [`CreateTaskResult`] (`resultType: "task"`) instead of the standard result.
|
||||
//! The client then polls `tasks/get`, answers in-task server-to-client requests
|
||||
//! via `tasks/update`, and may signal cancellation via `tasks/cancel`.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::MetaObject;
|
||||
use super::{InputRequests, JsonObject, MetaObject, ResultType};
|
||||
|
||||
/// Metadata for augmenting a request with task execution (spec `TaskMetadata`).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct TaskMetadata {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub ttl: Option<u64>,
|
||||
}
|
||||
/// Extension identifier for the MCP Tasks extension (SEP-2663).
|
||||
pub const TASKS_EXTENSION_ID: &str = "io.modelcontextprotocol/tasks";
|
||||
|
||||
impl TaskMetadata {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn with_ttl(mut self, ttl: u64) -> Self {
|
||||
self.ttl = Some(ttl);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata for associating messages with a task (spec `RelatedTaskMetadata`).
|
||||
///
|
||||
/// Carried in `_meta` under the key `"io.modelcontextprotocol/related-task"`.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct RelatedTaskMetadata {
|
||||
pub task_id: String,
|
||||
}
|
||||
|
||||
impl RelatedTaskMetadata {
|
||||
pub fn new(task_id: impl Into<String>) -> Self {
|
||||
Self {
|
||||
task_id: task_id.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The well-known `_meta` key for related-task metadata.
|
||||
pub const META_KEY: &str = "io.modelcontextprotocol/related-task";
|
||||
}
|
||||
|
||||
/// Canonical task lifecycle status as defined by SEP-1686.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
/// Canonical task lifecycle status (SEP-2663).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub enum TaskStatus {
|
||||
/// The receiver accepted the request and is currently working on it.
|
||||
/// The request is currently being processed.
|
||||
#[default]
|
||||
Working,
|
||||
/// The receiver requires additional input before work can continue.
|
||||
/// The server needs input from the client before the task can proceed.
|
||||
InputRequired,
|
||||
/// The underlying operation completed successfully and the result is ready.
|
||||
/// The request completed successfully and the result is available.
|
||||
/// This includes tool calls that returned results with `isError: true`.
|
||||
Completed,
|
||||
/// The underlying operation failed and will not continue.
|
||||
/// The request failed due to a JSON-RPC error during execution.
|
||||
Failed,
|
||||
/// The task was cancelled and will not continue processing.
|
||||
/// The request was cancelled before completion.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// Primary Task object that surfaces metadata during the task lifecycle.
|
||||
///
|
||||
/// Per spec, `lastUpdatedAt` and `ttl` are required fields.
|
||||
/// `ttl` is nullable (`null` means unlimited retention).
|
||||
impl TaskStatus {
|
||||
/// Returns `true` for terminal statuses (`completed`, `failed`, `cancelled`).
|
||||
pub fn is_terminal(&self) -> bool {
|
||||
matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
|
||||
}
|
||||
}
|
||||
|
||||
/// Operational metadata about ongoing work (spec `Task`, SEP-2663).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct Task {
|
||||
/// Unique task identifier generated by the receiver.
|
||||
/// Stable identifier for this task, generated by the server.
|
||||
pub task_id: String,
|
||||
/// Current lifecycle status (see [`TaskStatus`]).
|
||||
/// Current task status.
|
||||
pub status: TaskStatus,
|
||||
/// Optional human-readable status message for UI surfaces.
|
||||
/// Optional message describing the current task state.
|
||||
/// This MAY be exposed to the end-user or model.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub status_message: Option<String>,
|
||||
/// ISO-8601 creation timestamp.
|
||||
/// ISO 8601 timestamp when the task was created.
|
||||
pub created_at: String,
|
||||
/// ISO-8601 timestamp for the most recent status change.
|
||||
/// ISO 8601 timestamp when the task was last updated.
|
||||
pub last_updated_at: String,
|
||||
/// Retention window in milliseconds that the receiver agreed to honor.
|
||||
/// `None` (serialized as `null`) means unlimited retention.
|
||||
pub ttl: Option<u64>,
|
||||
/// Suggested polling interval (milliseconds).
|
||||
/// Time-to-live duration from creation in integer milliseconds; `None`
|
||||
/// (serialized as `null`) means unlimited. The server may discard the task
|
||||
/// after the TTL elapses. This value MAY change over the lifetime of a task.
|
||||
pub ttl_ms: Option<u64>,
|
||||
/// Suggested polling interval in integer milliseconds. Clients SHOULD honor
|
||||
/// this value to avoid overwhelming the server. This value MAY change over
|
||||
/// the lifetime of a task.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub poll_interval: Option<u64>,
|
||||
pub poll_interval_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl Task {
|
||||
/// Create a new Task with required fields.
|
||||
/// Create a new task with required fields.
|
||||
pub fn new(
|
||||
task_id: String,
|
||||
task_id: impl Into<String>,
|
||||
status: TaskStatus,
|
||||
created_at: String,
|
||||
last_updated_at: String,
|
||||
created_at: impl Into<String>,
|
||||
last_updated_at: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
task_id,
|
||||
task_id: task_id.into(),
|
||||
status,
|
||||
status_message: None,
|
||||
created_at,
|
||||
last_updated_at,
|
||||
ttl: None,
|
||||
poll_interval: None,
|
||||
created_at: created_at.into(),
|
||||
last_updated_at: last_updated_at.into(),
|
||||
ttl_ms: None,
|
||||
poll_interval_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -119,33 +95,241 @@ impl Task {
|
|||
}
|
||||
|
||||
/// Set the TTL in milliseconds. `None` means unlimited retention.
|
||||
pub fn with_ttl(mut self, ttl: u64) -> Self {
|
||||
self.ttl = Some(ttl);
|
||||
pub fn with_ttl_ms(mut self, ttl_ms: u64) -> Self {
|
||||
self.ttl_ms = Some(ttl_ms);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the poll interval in milliseconds.
|
||||
pub fn with_poll_interval(mut self, poll_interval: u64) -> Self {
|
||||
self.poll_interval = Some(poll_interval);
|
||||
/// Set the suggested poll interval in milliseconds.
|
||||
pub fn with_poll_interval_ms(mut self, poll_interval_ms: u64) -> Self {
|
||||
self.poll_interval_ms = Some(poll_interval_ms);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrapper returned by task-augmented requests (CreateTaskResult in SEP-1686).
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
/// Status-specific payload carried alongside the base [`Task`] fields in a
|
||||
/// [`DetailedTask`].
|
||||
///
|
||||
/// Mirrors the spec's `WorkingTask` / `InputRequiredTask` / `CompletedTask` /
|
||||
/// `FailedTask` / `CancelledTask` union: the variant is discriminated by the
|
||||
/// `status` field on the wire, with the payload fields inlined at the top level.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum TaskPayload {
|
||||
/// `status: "working"` — no additional payload.
|
||||
Working,
|
||||
/// `status: "input_required"` — outstanding server-to-client requests.
|
||||
InputRequired {
|
||||
/// Server-to-client requests that need to be fulfilled during task
|
||||
/// execution. Keys are arbitrary identifiers for matching requests
|
||||
/// to responses, unique over the lifetime of the task.
|
||||
input_requests: InputRequests,
|
||||
},
|
||||
/// `status: "completed"` — the final result of the task. The structure
|
||||
/// matches the result type of the original request (e.g. `CallToolResult`).
|
||||
Completed {
|
||||
/// The final result of the original request.
|
||||
result: JsonObject,
|
||||
},
|
||||
/// `status: "failed"` — the JSON-RPC error that caused the task to fail.
|
||||
Failed {
|
||||
/// The JSON-RPC error object.
|
||||
error: JsonObject,
|
||||
},
|
||||
/// `status: "cancelled"` — no additional payload.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
impl TaskPayload {
|
||||
/// The [`TaskStatus`] this payload corresponds to.
|
||||
pub fn status(&self) -> TaskStatus {
|
||||
match self {
|
||||
Self::Working => TaskStatus::Working,
|
||||
Self::InputRequired { .. } => TaskStatus::InputRequired,
|
||||
Self::Completed { .. } => TaskStatus::Completed,
|
||||
Self::Failed { .. } => TaskStatus::Failed,
|
||||
Self::Cancelled => TaskStatus::Cancelled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A task with its status-specific payload inlined (spec `DetailedTask`).
|
||||
///
|
||||
/// Used by `tasks/get` responses ([`GetTaskResult`]) and `notifications/tasks`
|
||||
/// ([`TaskStatusNotificationParams`](crate::model::TaskStatusNotificationParams)).
|
||||
/// On the wire, the payload fields (`inputRequests` / `result` / `error`) are
|
||||
/// flattened at the top level next to the base [`Task`] fields, and `status`
|
||||
/// discriminates the variant.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct DetailedTask {
|
||||
/// Base task metadata. Its `status` always agrees with the payload.
|
||||
pub task: Task,
|
||||
/// Status-specific payload.
|
||||
pub payload: TaskPayload,
|
||||
}
|
||||
|
||||
impl DetailedTask {
|
||||
/// Build a `DetailedTask`, forcing `task.status` to match the payload.
|
||||
pub fn new(mut task: Task, payload: TaskPayload) -> Self {
|
||||
task.status = payload.status();
|
||||
Self { task, payload }
|
||||
}
|
||||
|
||||
/// The current status.
|
||||
pub fn status(&self) -> TaskStatus {
|
||||
self.task.status
|
||||
}
|
||||
}
|
||||
|
||||
// Wire shape helper: base Task fields + optional payload fields, all flattened.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
struct DetailedTaskWire {
|
||||
#[serde(flatten)]
|
||||
task: Task,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
input_requests: Option<InputRequests>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
result: Option<JsonObject>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
error: Option<JsonObject>,
|
||||
}
|
||||
|
||||
impl From<DetailedTask> for DetailedTaskWire {
|
||||
fn from(value: DetailedTask) -> Self {
|
||||
let DetailedTask { task, payload } = value;
|
||||
let (input_requests, result, error) = match payload {
|
||||
TaskPayload::Working | TaskPayload::Cancelled => (None, None, None),
|
||||
TaskPayload::InputRequired { input_requests } => (Some(input_requests), None, None),
|
||||
TaskPayload::Completed { result } => (None, Some(result), None),
|
||||
TaskPayload::Failed { error } => (None, None, Some(error)),
|
||||
};
|
||||
Self {
|
||||
task,
|
||||
input_requests,
|
||||
result,
|
||||
error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<DetailedTaskWire> for DetailedTask {
|
||||
type Error = String;
|
||||
fn try_from(wire: DetailedTaskWire) -> Result<Self, String> {
|
||||
let payload = match wire.task.status {
|
||||
TaskStatus::Working => TaskPayload::Working,
|
||||
TaskStatus::Cancelled => TaskPayload::Cancelled,
|
||||
TaskStatus::InputRequired => TaskPayload::InputRequired {
|
||||
input_requests: wire.input_requests.ok_or_else(|| {
|
||||
"task with status \"input_required\" is missing `inputRequests`".to_owned()
|
||||
})?,
|
||||
},
|
||||
TaskStatus::Completed => TaskPayload::Completed {
|
||||
result: wire.result.ok_or_else(|| {
|
||||
"task with status \"completed\" is missing `result`".to_owned()
|
||||
})?,
|
||||
},
|
||||
TaskStatus::Failed => TaskPayload::Failed {
|
||||
error: wire
|
||||
.error
|
||||
.ok_or_else(|| "task with status \"failed\" is missing `error`".to_owned())?,
|
||||
},
|
||||
};
|
||||
Ok(DetailedTask {
|
||||
task: wire.task,
|
||||
payload,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for DetailedTask {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
DetailedTaskWire::from(self.clone()).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for DetailedTask {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let wire = DetailedTaskWire::deserialize(deserializer)?;
|
||||
Self::try_from(wire).map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "schemars")]
|
||||
impl schemars::JsonSchema for DetailedTask {
|
||||
fn schema_name() -> std::borrow::Cow<'static, str> {
|
||||
"DetailedTask".into()
|
||||
}
|
||||
fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
|
||||
// The actual wire shape: base Task fields plus the optional
|
||||
// status-specific payload fields (inputRequests / result / error).
|
||||
<DetailedTaskWire as schemars::JsonSchema>::json_schema(generator)
|
||||
}
|
||||
}
|
||||
|
||||
/// Result returned in lieu of a standard result to indicate the request will
|
||||
/// be processed asynchronously (spec `CreateTaskResult`, `resultType: "task"`).
|
||||
///
|
||||
/// The embedded task is the seed state for the task; the client uses
|
||||
/// `task.task_id` for all subsequent `tasks/get`, `tasks/update`, and
|
||||
/// `tasks/cancel` calls.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct CreateTaskResult {
|
||||
/// Always `"task"`.
|
||||
pub result_type: ResultType,
|
||||
/// Seed state of the newly created task, flattened at the top level.
|
||||
#[serde(flatten)]
|
||||
pub task: Task,
|
||||
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
|
||||
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
|
||||
pub meta: Option<MetaObject>,
|
||||
}
|
||||
|
||||
// Custom deserializer that requires `resultType: "task"`. Without this,
|
||||
// `CreateTaskResult` would greedily match other task-shaped results (e.g.
|
||||
// `tasks/get` responses, which also carry `taskId`/`status` at the top level
|
||||
// but use `resultType: "complete"`) inside `#[serde(untagged)]` unions such
|
||||
// as `ServerResult`.
|
||||
impl<'de> Deserialize<'de> for CreateTaskResult {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Helper {
|
||||
result_type: ResultType,
|
||||
#[serde(flatten)]
|
||||
task: Task,
|
||||
#[serde(rename = "_meta", default)]
|
||||
meta: Option<MetaObject>,
|
||||
}
|
||||
let helper = Helper::deserialize(deserializer)?;
|
||||
if !helper.result_type.is_task() {
|
||||
return Err(serde::de::Error::custom(
|
||||
"CreateTaskResult requires resultType to be \"task\"",
|
||||
));
|
||||
}
|
||||
Ok(CreateTaskResult {
|
||||
result_type: helper.result_type,
|
||||
task: helper.task,
|
||||
meta: helper.meta,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl CreateTaskResult {
|
||||
/// Create a new CreateTaskResult.
|
||||
/// Create a new `CreateTaskResult` from the seed task state.
|
||||
pub fn new(task: Task) -> Self {
|
||||
Self { task, meta: None }
|
||||
Self {
|
||||
result_type: ResultType::TASK,
|
||||
task,
|
||||
meta: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the protocol-level metadata for this result.
|
||||
|
|
@ -155,80 +339,206 @@ impl CreateTaskResult {
|
|||
}
|
||||
}
|
||||
|
||||
/// Response to a `tasks/get` request.
|
||||
/// Response to a `tasks/get` request (spec `GetTaskResult = Result & DetailedTask`).
|
||||
///
|
||||
/// Per spec, `GetTaskResult = allOf[Result, Task]` — the Task fields are
|
||||
/// flattened at the top level, not nested under a `task` key.
|
||||
/// `resultType` is `"complete"` — this is the standard result shape for
|
||||
/// `tasks/get`, not a task handle.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct GetTaskResult {
|
||||
/// Result type discriminator. `tasks/get` responses are standard results:
|
||||
/// `"complete"` (SEP-2322). Absent values deserialize as `"complete"`.
|
||||
#[serde(default)]
|
||||
pub result_type: ResultType,
|
||||
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
|
||||
pub meta: Option<MetaObject>,
|
||||
/// The task with status-specific payload inlined.
|
||||
#[serde(flatten)]
|
||||
pub task: Task,
|
||||
pub task: DetailedTask,
|
||||
}
|
||||
|
||||
impl GetTaskResult {
|
||||
pub fn new(task: Task) -> Self {
|
||||
Self { meta: None, task }
|
||||
pub fn new(task: DetailedTask) -> Self {
|
||||
Self {
|
||||
result_type: ResultType::COMPLETE,
|
||||
meta: None,
|
||||
task,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Response to a `tasks/result` request.
|
||||
/// Empty acknowledgement for `tasks/update` and `tasks/cancel` (SEP-2663).
|
||||
///
|
||||
/// Per spec, the result structure matches the original request type
|
||||
/// (e.g., `CallToolResult` for `tools/call`). This is represented as
|
||||
/// an open object. The payload is the original request's result
|
||||
/// serialized as a JSON value.
|
||||
/// The spec requires these acks to be empty results carrying the SEP-2322
|
||||
/// `resultType: "complete"` discriminator; task state changes are observed
|
||||
/// via the next `tasks/get`.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct GetTaskPayloadResult(pub Value);
|
||||
|
||||
impl GetTaskPayloadResult {
|
||||
/// Create a new GetTaskPayloadResult with the given value.
|
||||
pub fn new(value: Value) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
pub struct TaskAckResult {
|
||||
/// Always `"complete"`.
|
||||
pub result_type: ResultType,
|
||||
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
|
||||
pub meta: Option<MetaObject>,
|
||||
}
|
||||
|
||||
// Custom Deserialize that always fails, so that `GetTaskPayloadResult` is skipped
|
||||
// during `#[serde(untagged)]` enum deserialization (e.g. `ServerResult`).
|
||||
// The payload has the same JSON shape as `CustomResult(Value)`, so they are
|
||||
// indistinguishable. `CustomResult` acts as the catch-all instead.
|
||||
// `GetTaskPayloadResult` should be constructed programmatically via `::new()`.
|
||||
impl<'de> serde::Deserialize<'de> for GetTaskPayloadResult {
|
||||
// Custom deserializer that requires `resultType: "complete"` and rejects any
|
||||
// other fields. Without this, `TaskAckResult` would greedily match arbitrary
|
||||
// result objects carrying a `resultType` key inside `#[serde(untagged)]`
|
||||
// unions such as `ServerResult`, shadowing `CustomResult` and losing data.
|
||||
impl<'de> Deserialize<'de> for TaskAckResult {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
// Consume the value so the deserializer state stays consistent.
|
||||
serde::de::IgnoredAny::deserialize(deserializer)?;
|
||||
Err(serde::de::Error::custom(
|
||||
"GetTaskPayloadResult cannot be deserialized directly; \
|
||||
use CustomResult as the catch-all",
|
||||
))
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct Helper {
|
||||
result_type: ResultType,
|
||||
#[serde(rename = "_meta", default)]
|
||||
meta: Option<MetaObject>,
|
||||
}
|
||||
let helper = Helper::deserialize(deserializer)?;
|
||||
if !helper.result_type.is_complete() {
|
||||
return Err(serde::de::Error::custom(
|
||||
"TaskAckResult requires resultType to be \"complete\"",
|
||||
));
|
||||
}
|
||||
Ok(TaskAckResult {
|
||||
result_type: helper.result_type,
|
||||
meta: helper.meta,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Response to a `tasks/cancel` request.
|
||||
///
|
||||
/// Per spec, `CancelTaskResult = allOf[Result, Task]` — same shape as `GetTaskResult`.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct CancelTaskResult {
|
||||
#[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
|
||||
pub meta: Option<MetaObject>,
|
||||
#[serde(flatten)]
|
||||
pub task: Task,
|
||||
}
|
||||
|
||||
impl CancelTaskResult {
|
||||
pub fn new(task: Task) -> Self {
|
||||
Self { meta: None, task }
|
||||
impl Default for TaskAckResult {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
result_type: ResultType::COMPLETE,
|
||||
meta: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TaskAckResult {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn base_task(status: TaskStatus) -> Task {
|
||||
Task::new(
|
||||
"task-1",
|
||||
status,
|
||||
"2025-11-25T10:30:00Z",
|
||||
"2025-11-25T10:40:00Z",
|
||||
)
|
||||
.with_ttl_ms(60000)
|
||||
.with_poll_interval_ms(5000)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_task_result_wire_shape() {
|
||||
let result = CreateTaskResult::new(base_task(TaskStatus::Working));
|
||||
let value = serde_json::to_value(&result).unwrap();
|
||||
assert_eq!(
|
||||
value,
|
||||
json!({
|
||||
"resultType": "task",
|
||||
"taskId": "task-1",
|
||||
"status": "working",
|
||||
"createdAt": "2025-11-25T10:30:00Z",
|
||||
"lastUpdatedAt": "2025-11-25T10:40:00Z",
|
||||
"ttlMs": 60000,
|
||||
"pollIntervalMs": 5000
|
||||
})
|
||||
);
|
||||
let roundtrip: CreateTaskResult = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(roundtrip, result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ttl_ms_null_means_unlimited() {
|
||||
let mut task = base_task(TaskStatus::Working);
|
||||
task.ttl_ms = None;
|
||||
let value = serde_json::to_value(&task).unwrap();
|
||||
assert_eq!(value["ttlMs"], serde_json::Value::Null);
|
||||
let roundtrip: Task = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(roundtrip.ttl_ms, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detailed_task_completed_roundtrip() {
|
||||
let detailed = DetailedTask::new(
|
||||
base_task(TaskStatus::Working),
|
||||
TaskPayload::Completed {
|
||||
result: serde_json::from_value(json!({
|
||||
"content": [{"type": "text", "text": "ok"}],
|
||||
"isError": false
|
||||
}))
|
||||
.unwrap(),
|
||||
},
|
||||
);
|
||||
// Status is forced to match the payload.
|
||||
assert_eq!(detailed.status(), TaskStatus::Completed);
|
||||
let value = serde_json::to_value(&detailed).unwrap();
|
||||
assert_eq!(value["status"], "completed");
|
||||
assert_eq!(value["result"]["isError"], false);
|
||||
let roundtrip: DetailedTask = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(roundtrip, detailed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detailed_task_input_required_requires_input_requests() {
|
||||
let err = serde_json::from_value::<DetailedTask>(json!({
|
||||
"taskId": "task-1",
|
||||
"status": "input_required",
|
||||
"createdAt": "2025-11-25T10:30:00Z",
|
||||
"lastUpdatedAt": "2025-11-25T10:40:00Z",
|
||||
"ttlMs": null
|
||||
}))
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("inputRequests"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detailed_task_failed_roundtrip() {
|
||||
let detailed = DetailedTask::new(
|
||||
base_task(TaskStatus::Failed),
|
||||
TaskPayload::Failed {
|
||||
error: serde_json::from_value(json!({
|
||||
"code": -32603,
|
||||
"message": "boom"
|
||||
}))
|
||||
.unwrap(),
|
||||
},
|
||||
);
|
||||
let value = serde_json::to_value(&detailed).unwrap();
|
||||
assert_eq!(value["status"], "failed");
|
||||
assert_eq!(value["error"]["code"], -32603);
|
||||
let roundtrip: DetailedTask = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(roundtrip, detailed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_task_result_flattens_detailed_task() {
|
||||
let result = GetTaskResult::new(DetailedTask::new(
|
||||
base_task(TaskStatus::Working),
|
||||
TaskPayload::Working,
|
||||
));
|
||||
let value = serde_json::to_value(&result).unwrap();
|
||||
assert_eq!(value["taskId"], "task-1");
|
||||
assert_eq!(value["status"], "working");
|
||||
let roundtrip: GetTaskResult = serde_json::from_value(value).unwrap();
|
||||
assert_eq!(roundtrip, result);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,9 +31,6 @@ pub struct Tool {
|
|||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
/// Optional additional tool information.
|
||||
pub annotations: Option<ToolAnnotations>,
|
||||
/// Execution-related configuration including task support mode.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub execution: Option<ToolExecution>,
|
||||
/// Optional list of icons for the tool
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub icons: Option<Vec<Icon>>,
|
||||
|
|
@ -42,62 +39,6 @@ pub struct Tool {
|
|||
pub meta: Option<MetaObject>,
|
||||
}
|
||||
|
||||
/// Per-tool task support mode as defined in the MCP specification.
|
||||
///
|
||||
/// This enum indicates whether a tool supports task-based invocation,
|
||||
/// allowing clients to know how to properly call the tool.
|
||||
///
|
||||
/// See [Tool-Level Negotiation](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/tasks#tool-level-negotiation).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[expect(clippy::exhaustive_enums, reason = "intentionally exhaustive")]
|
||||
pub enum TaskSupport {
|
||||
/// Clients MUST NOT invoke this tool as a task (default behavior).
|
||||
#[default]
|
||||
Forbidden,
|
||||
/// Clients MAY invoke this tool as either a task or a normal call.
|
||||
Optional,
|
||||
/// Clients MUST invoke this tool as a task.
|
||||
Required,
|
||||
}
|
||||
|
||||
/// Execution-related configuration for a tool.
|
||||
///
|
||||
/// This struct contains settings that control how a tool should be executed,
|
||||
/// including task support configuration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
|
||||
#[non_exhaustive]
|
||||
pub struct ToolExecution {
|
||||
/// Indicates whether this tool supports task-based invocation.
|
||||
///
|
||||
/// When not present or set to `Forbidden`, clients MUST NOT invoke this tool as a task.
|
||||
/// When set to `Optional`, clients MAY invoke this tool as a task or normal call.
|
||||
/// When set to `Required`, clients MUST invoke this tool as a task.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub task_support: Option<TaskSupport>,
|
||||
}
|
||||
|
||||
impl ToolExecution {
|
||||
/// Create a new empty ToolExecution configuration.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Create a ToolExecution from raw optional fields.
|
||||
pub fn from_raw(task_support: Option<TaskSupport>) -> Self {
|
||||
Self { task_support }
|
||||
}
|
||||
|
||||
/// Set the task support mode.
|
||||
pub fn with_task_support(mut self, task_support: TaskSupport) -> Self {
|
||||
self.task_support = Some(task_support);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Additional properties describing a Tool to clients.
|
||||
///
|
||||
/// NOTE: all properties in ToolAnnotations are **hints**.
|
||||
|
|
@ -232,7 +173,6 @@ impl Tool {
|
|||
input_schema: input_schema.into(),
|
||||
output_schema: None,
|
||||
annotations: None,
|
||||
execution: None,
|
||||
icons: None,
|
||||
meta: None,
|
||||
}
|
||||
|
|
@ -255,7 +195,6 @@ impl Tool {
|
|||
input_schema: input_schema.into(),
|
||||
output_schema: None,
|
||||
annotations: None,
|
||||
execution: None,
|
||||
icons: None,
|
||||
meta: None,
|
||||
}
|
||||
|
|
@ -298,22 +237,6 @@ impl Tool {
|
|||
}
|
||||
}
|
||||
|
||||
/// Set the execution configuration for this tool.
|
||||
pub fn with_execution(mut self, execution: ToolExecution) -> Self {
|
||||
self.execution = Some(execution);
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the task support mode for this tool.
|
||||
///
|
||||
/// Returns `TaskSupport::Forbidden` if not explicitly set.
|
||||
pub fn task_support(&self) -> TaskSupport {
|
||||
self.execution
|
||||
.as_ref()
|
||||
.and_then(|e| e.task_support)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Set the output schema using a type that implements JsonSchema
|
||||
#[cfg(feature = "server")]
|
||||
pub fn with_output_schema<T: JsonSchema + 'static>(mut self) -> Self {
|
||||
|
|
|
|||
Loading…
Reference in a new issue