* 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.
360 lines
12 KiB
Rust
360 lines
12 KiB
Rust
#![allow(dead_code)]
|
|
use std::sync::Arc;
|
|
|
|
use rmcp::{
|
|
ErrorData as McpError, RoleServer, ServerHandler,
|
|
handler::server::{
|
|
router::{prompt::PromptRouter, tool::ToolRouter},
|
|
wrapper::Parameters,
|
|
},
|
|
model::*,
|
|
prompt, prompt_handler, prompt_router, schemars,
|
|
service::RequestContext,
|
|
tool, tool_handler, tool_router,
|
|
};
|
|
use serde_json::json;
|
|
use tokio::sync::Mutex;
|
|
|
|
#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
|
|
pub struct StructRequest {
|
|
pub a: i32,
|
|
pub b: i32,
|
|
}
|
|
|
|
#[derive(Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
|
|
pub struct ExamplePromptArgs {
|
|
/// A message to put in the prompt
|
|
pub message: String,
|
|
}
|
|
|
|
/// MCP spec types prompt arguments as `Record<string, string>`, so
|
|
/// spec-compliant clients stringify all values. Accept both wire forms.
|
|
fn deserialize_i32_from_string_or_int<'de, D>(deserializer: D) -> Result<i32, D::Error>
|
|
where
|
|
D: serde::Deserializer<'de>,
|
|
{
|
|
use serde::Deserialize;
|
|
#[derive(Deserialize)]
|
|
#[serde(untagged)]
|
|
enum StringOrInt {
|
|
Int(i32),
|
|
Str(String),
|
|
}
|
|
match StringOrInt::deserialize(deserializer)? {
|
|
StringOrInt::Int(n) => Ok(n),
|
|
StringOrInt::Str(s) => s.parse::<i32>().map_err(serde::de::Error::custom),
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
|
|
pub struct CounterAnalysisArgs {
|
|
/// The target value you're trying to reach
|
|
#[serde(deserialize_with = "deserialize_i32_from_string_or_int")]
|
|
pub goal: i32,
|
|
/// Preferred strategy: 'fast' or 'careful'
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub strategy: Option<String>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Counter {
|
|
counter: Arc<Mutex<i32>>,
|
|
tool_router: ToolRouter<Counter>,
|
|
prompt_router: PromptRouter<Counter>,
|
|
}
|
|
|
|
#[tool_router]
|
|
impl Counter {
|
|
#[allow(dead_code)]
|
|
pub fn new() -> Self {
|
|
Self {
|
|
counter: Arc::new(Mutex::new(0)),
|
|
tool_router: Self::tool_router(),
|
|
prompt_router: Self::prompt_router(),
|
|
}
|
|
}
|
|
|
|
fn _create_resource_text(&self, uri: &str, name: &str) -> Resource {
|
|
Resource::new(uri, name.to_string())
|
|
}
|
|
|
|
#[tool(description = "Increment the counter by 1")]
|
|
async fn increment(&self) -> Result<CallToolResult, McpError> {
|
|
let mut counter = self.counter.lock().await;
|
|
*counter += 1;
|
|
Ok(CallToolResult::success(vec![ContentBlock::text(
|
|
counter.to_string(),
|
|
)]))
|
|
}
|
|
|
|
#[tool(description = "Decrement the counter by 1")]
|
|
async fn decrement(&self) -> Result<CallToolResult, McpError> {
|
|
let mut counter = self.counter.lock().await;
|
|
*counter -= 1;
|
|
Ok(CallToolResult::success(vec![ContentBlock::text(
|
|
counter.to_string(),
|
|
)]))
|
|
}
|
|
|
|
#[tool(description = "Get the current counter value")]
|
|
async fn get_value(&self) -> Result<CallToolResult, McpError> {
|
|
let counter = self.counter.lock().await;
|
|
Ok(CallToolResult::success(vec![ContentBlock::text(
|
|
counter.to_string(),
|
|
)]))
|
|
}
|
|
|
|
#[tool(description = "Long running task example")]
|
|
async fn long_task(&self) -> Result<CallToolResult, McpError> {
|
|
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
|
Ok(CallToolResult::success(vec![ContentBlock::text(
|
|
"Long task completed",
|
|
)]))
|
|
}
|
|
|
|
#[tool(description = "Say hello to the client")]
|
|
fn say_hello(&self) -> Result<CallToolResult, McpError> {
|
|
Ok(CallToolResult::success(vec![ContentBlock::text("hello")]))
|
|
}
|
|
|
|
#[tool(description = "Repeat what you say")]
|
|
fn echo(&self, Parameters(object): Parameters<JsonObject>) -> Result<CallToolResult, McpError> {
|
|
Ok(CallToolResult::success(vec![ContentBlock::text(
|
|
serde_json::Value::Object(object).to_string(),
|
|
)]))
|
|
}
|
|
|
|
#[tool(description = "Calculate the sum of two numbers")]
|
|
fn sum(
|
|
&self,
|
|
Parameters(StructRequest { a, b }): Parameters<StructRequest>,
|
|
) -> Result<CallToolResult, McpError> {
|
|
Ok(CallToolResult::success(vec![ContentBlock::text(
|
|
(a + b).to_string(),
|
|
)]))
|
|
}
|
|
|
|
/// Returns the `Mcp-Session-Id` of the current session (streamable HTTP only).
|
|
#[tool(description = "Get the session ID for this connection")]
|
|
fn get_session_id(&self, ctx: RequestContext<RoleServer>) -> Result<CallToolResult, McpError> {
|
|
let session_id = ctx
|
|
.extensions
|
|
.get::<axum::http::request::Parts>()
|
|
.and_then(|parts| parts.headers.get("mcp-session-id"))
|
|
.map(|v| v.to_str().unwrap_or("(non-ascii)").to_owned());
|
|
|
|
match session_id {
|
|
Some(id) => Ok(CallToolResult::success(vec![ContentBlock::text(id)])),
|
|
None => Ok(CallToolResult::success(vec![ContentBlock::text(
|
|
"no session (not running over streamable HTTP?)",
|
|
)])),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[prompt_router]
|
|
impl Counter {
|
|
/// This is an example prompt that takes one required argument, message
|
|
#[prompt(
|
|
name = "example_prompt",
|
|
meta = MetaObject(rmcp::object!({"meta_key": "meta_value"}))
|
|
)]
|
|
async fn example_prompt(
|
|
&self,
|
|
Parameters(args): Parameters<ExamplePromptArgs>,
|
|
_ctx: RequestContext<RoleServer>,
|
|
) -> Result<Vec<PromptMessage>, McpError> {
|
|
let prompt = format!(
|
|
"This is an example prompt with your message here: '{}'",
|
|
args.message
|
|
);
|
|
Ok(vec![PromptMessage::new_text(Role::User, prompt)])
|
|
}
|
|
|
|
/// Analyze the current counter value and suggest next steps
|
|
#[prompt(name = "counter_analysis")]
|
|
async fn counter_analysis(
|
|
&self,
|
|
Parameters(args): Parameters<CounterAnalysisArgs>,
|
|
_ctx: RequestContext<RoleServer>,
|
|
) -> Result<GetPromptResult, McpError> {
|
|
let strategy = args.strategy.unwrap_or_else(|| "careful".to_string());
|
|
let current_value = *self.counter.lock().await;
|
|
let difference = args.goal - current_value;
|
|
|
|
let messages = vec![
|
|
PromptMessage::new_text(
|
|
Role::Assistant,
|
|
"I'll analyze the counter situation and suggest the best approach.",
|
|
),
|
|
PromptMessage::new_text(
|
|
Role::User,
|
|
format!(
|
|
"Current counter value: {}\nGoal value: {}\nDifference: {}\nStrategy preference: {}\n\nPlease analyze the situation and suggest the best approach to reach the goal.",
|
|
current_value, args.goal, difference, strategy
|
|
),
|
|
),
|
|
];
|
|
|
|
Ok(GetPromptResult::new(messages).with_description(format!(
|
|
"Counter analysis for reaching {} from {}",
|
|
args.goal, current_value
|
|
)))
|
|
}
|
|
}
|
|
|
|
#[tool_handler(meta = MetaObject(rmcp::object!({"tool_meta_key": "tool_meta_value"})))]
|
|
#[prompt_handler(meta = MetaObject(rmcp::object!({"router_meta_key": "router_meta_value"})))]
|
|
impl ServerHandler for Counter {
|
|
fn get_info(&self) -> ServerInfo {
|
|
ServerInfo::new(
|
|
ServerCapabilities::builder()
|
|
.enable_prompts()
|
|
.enable_resources()
|
|
.enable_tools()
|
|
.build(),
|
|
)
|
|
.with_server_info(Implementation::from_build_env())
|
|
.with_protocol_version(ProtocolVersion::V_2024_11_05)
|
|
.with_instructions("This server provides counter tools and prompts. Tools: increment, decrement, get_value, say_hello, echo, sum. Prompts: example_prompt (takes a message), counter_analysis (analyzes counter state with a goal).".to_string())
|
|
}
|
|
|
|
async fn list_resources(
|
|
&self,
|
|
_request: Option<PaginatedRequestParams>,
|
|
_: RequestContext<RoleServer>,
|
|
) -> Result<ListResourcesResult, McpError> {
|
|
Ok(ListResourcesResult {
|
|
resources: vec![
|
|
self._create_resource_text("str:////Users/to/some/path/", "cwd"),
|
|
self._create_resource_text("memo://insights", "memo-name"),
|
|
],
|
|
..Default::default()
|
|
})
|
|
}
|
|
|
|
async fn read_resource(
|
|
&self,
|
|
request: ReadResourceRequestParams,
|
|
_: RequestContext<RoleServer>,
|
|
) -> Result<ReadResourceResponse, McpError> {
|
|
let uri = &request.uri;
|
|
match uri.as_str() {
|
|
"str:////Users/to/some/path/" => {
|
|
let cwd = "/Users/to/some/path/";
|
|
Ok(ReadResourceResult::new(vec![ResourceContents::text(cwd, uri.clone())]).into())
|
|
}
|
|
"memo://insights" => {
|
|
let memo = "Business Intelligence Memo\n\nAnalysis has revealed 5 key insights ...";
|
|
Ok(ReadResourceResult::new(vec![ResourceContents::text(memo, uri.clone())]).into())
|
|
}
|
|
_ => Err(McpError::resource_not_found(
|
|
"resource_not_found",
|
|
Some(json!({
|
|
"uri": uri
|
|
})),
|
|
)),
|
|
}
|
|
}
|
|
|
|
async fn list_resource_templates(
|
|
&self,
|
|
_request: Option<PaginatedRequestParams>,
|
|
_: RequestContext<RoleServer>,
|
|
) -> Result<ListResourceTemplatesResult, McpError> {
|
|
Ok(ListResourceTemplatesResult {
|
|
resource_templates: Vec::new(),
|
|
..Default::default()
|
|
})
|
|
}
|
|
|
|
async fn initialize(
|
|
&self,
|
|
_request: InitializeRequestParams,
|
|
context: RequestContext<RoleServer>,
|
|
) -> Result<InitializeResult, McpError> {
|
|
if let Some(http_request_part) = context.extensions.get::<axum::http::request::Parts>() {
|
|
let initialize_headers = &http_request_part.headers;
|
|
let initialize_uri = &http_request_part.uri;
|
|
tracing::info!(?initialize_headers, %initialize_uri, "initialize from http server");
|
|
}
|
|
Ok(self.get_info())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use rmcp::{ClientHandler, ServiceExt};
|
|
use tokio::time::Duration;
|
|
|
|
use super::*;
|
|
|
|
#[derive(Default, Clone)]
|
|
struct TestClient;
|
|
|
|
impl ClientHandler for TestClient {}
|
|
|
|
#[tokio::test]
|
|
async fn test_prompt_attributes_generated() {
|
|
// Verify that the prompt macros generate the expected attributes
|
|
let example_attr = Counter::example_prompt_prompt_attr();
|
|
assert_eq!(example_attr.name, "example_prompt");
|
|
assert!(example_attr.description.is_some());
|
|
assert!(example_attr.arguments.is_some());
|
|
|
|
let args = example_attr.arguments.unwrap();
|
|
assert_eq!(args.len(), 1);
|
|
assert_eq!(args[0].name, "message");
|
|
assert_eq!(args[0].required, Some(true));
|
|
|
|
let analysis_attr = Counter::counter_analysis_prompt_attr();
|
|
assert_eq!(analysis_attr.name, "counter_analysis");
|
|
assert!(analysis_attr.description.is_some());
|
|
assert!(analysis_attr.arguments.is_some());
|
|
|
|
let args = analysis_attr.arguments.unwrap();
|
|
assert_eq!(args.len(), 2);
|
|
assert_eq!(args[0].name, "goal");
|
|
assert_eq!(args[0].required, Some(true));
|
|
assert_eq!(args[1].name, "strategy");
|
|
assert_eq!(args[1].required, Some(false));
|
|
}
|
|
|
|
#[test]
|
|
fn test_counter_analysis_args_accepts_integer_goal() {
|
|
let json = serde_json::json!({ "goal": 20 });
|
|
let args: CounterAnalysisArgs = serde_json::from_value(json).unwrap();
|
|
assert_eq!(args.goal, 20);
|
|
}
|
|
|
|
#[test]
|
|
fn test_counter_analysis_args_accepts_string_goal() {
|
|
let json = serde_json::json!({ "goal": "20" });
|
|
let args: CounterAnalysisArgs = serde_json::from_value(json).unwrap();
|
|
assert_eq!(args.goal, 20);
|
|
}
|
|
|
|
#[test]
|
|
fn test_counter_analysis_args_accepts_negative_string_goal() {
|
|
let json = serde_json::json!({ "goal": "-7" });
|
|
let args: CounterAnalysisArgs = serde_json::from_value(json).unwrap();
|
|
assert_eq!(args.goal, -7);
|
|
}
|
|
|
|
#[test]
|
|
fn test_counter_analysis_args_rejects_non_numeric_string_goal() {
|
|
let json = serde_json::json!({ "goal": "not a number" });
|
|
let result: Result<CounterAnalysisArgs, _> = serde_json::from_value(json);
|
|
assert!(result.is_err());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn test_prompt_router_has_routes() {
|
|
let router = Counter::prompt_router();
|
|
assert!(router.has_route("example_prompt"));
|
|
assert!(router.has_route("counter_analysis"));
|
|
|
|
let prompts = router.list_all();
|
|
assert_eq!(prompts.len(), 2);
|
|
}
|
|
}
|