mod caller;
mod card;
mod executor;
mod http;
mod task;
pub use caller::{AnonymousCallers, McpCaller, McpCallerResolver, McpHttpRequest};
pub use card::{
AI_CATALOG_MEDIA_TYPE, AI_CATALOG_SPEC_VERSION, AI_CATALOG_WELL_KNOWN_PATH, AiCatalog,
AiCatalogContent, AiCatalogEntry, AiCatalogHost, IconTheme, InputFormat, RemoteTransport,
SERVER_CARD_ENDPOINT_SUFFIX, SERVER_CARD_MEDIA_TYPE, SERVER_CARD_SCHEMA_URL,
SERVER_CARD_WELL_KNOWN_PATH, ServerCard, ServerCardHeader, ServerCardIcon, ServerCardInput,
ServerCardRemote, ServerCardRepository,
};
pub use executor::{
GovernedExecutor, McpCallExecutor, McpToolCall, McpToolOutcome, UngovernedExecutor,
};
pub use http::{McpRouterBuilder, McpSessions};
pub use task::{McpRequestPeer, McpTaskHost};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use adk_core::{
AdkError, ErrorCategory, ErrorComponent, Result, RetryHint, RunConfig,
TOOL_ERROR_MESSAGE_LIMIT, Tool, ToolEffect, Url, tool_error_response,
};
use rmcp::model::{
CallToolRequestParams, CallToolResponse, CallToolResult, CancelTaskParams, ContentBlock,
CreateTaskResult, ErrorCode, ErrorData, GetTaskParams, GetTaskResult, Implementation,
InitializeResult, InputRequiredResult, JsonObject, ListToolsResult, PaginatedRequestParams,
ProtocolVersion, ServerCapabilities, ServerConfig, ToolAnnotations, UpdateTaskParams,
};
use rmcp::service::RequestContext;
use rmcp::{RoleServer, ServerHandler};
use serde_json::{Value, json};
use crate::ToolArgumentValidator;
pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(60);
const QUOTED_NAME_LIMIT: usize = 128;
#[derive(Clone)]
pub struct McpServer {
inner: Arc<Inner>,
}
struct Inner {
name: String,
version: String,
description: String,
title: Option<String>,
website_url: Option<String>,
repository: Option<ServerCardRepository>,
icons: Vec<ServerCardIcon>,
instructions: Option<String>,
entries: Vec<Entry>,
index: HashMap<String, usize>,
executor: Arc<dyn McpCallExecutor>,
task_host: Option<Arc<dyn McpTaskHost>>,
local_caller: McpCaller,
call_timeout: Option<Duration>,
}
struct Entry {
tool: Arc<dyn Tool>,
definition: rmcp::model::Tool,
validator: ToolArgumentValidator,
}
impl std::fmt::Debug for McpServer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let tools: Vec<&str> = self.inner.entries.iter().map(|entry| entry.tool.name()).collect();
f.debug_struct("McpServer")
.field("name", &self.inner.name)
.field("version", &self.inner.version)
.field("tools", &tools)
.finish_non_exhaustive()
}
}
impl McpServer {
pub fn builder(name: impl Into<String>, version: impl Into<String>) -> McpServerBuilder {
McpServerBuilder::new(name, version)
}
pub fn name(&self) -> &str {
&self.inner.name
}
pub fn version(&self) -> &str {
&self.inner.version
}
pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
self.inner.entries.iter().map(|entry| Arc::clone(&entry.tool)).collect()
}
pub fn tool_definitions(&self) -> Vec<rmcp::model::Tool> {
self.inner.entries.iter().map(|entry| entry.definition.clone()).collect()
}
pub fn tool_definitions_for(&self, caller: &McpCaller) -> Vec<rmcp::model::Tool> {
self.inner
.entries
.iter()
.filter(|entry| self.inner.executor.is_visible(entry.tool.as_ref(), caller))
.map(|entry| entry.definition.clone())
.collect()
}
pub fn server_card(&self, endpoint: &Url, headers: &[ServerCardHeader]) -> ServerCard {
let inner = &self.inner;
let versions = ServerHandler::supported_protocol_versions(self);
let mut remote = ServerCardRemote::new(RemoteTransport::StreamableHttp, endpoint.as_str())
.with_protocol_versions(versions.iter().map(ToString::to_string));
for header in headers {
remote = remote.with_header(header.clone());
}
ServerCard {
schema: SERVER_CARD_SCHEMA_URL.to_string(),
name: inner.name.clone(),
version: inner.version.clone(),
description: inner.description.clone(),
title: inner.title.clone(),
website_url: inner.website_url.clone(),
repository: inner.repository.clone(),
icons: (!inner.icons.is_empty()).then(|| inner.icons.clone()),
remotes: Some(vec![remote]),
meta: None,
}
}
pub fn ai_catalog_entry(&self, card_url: &Url) -> AiCatalogEntry {
AiCatalogEntry::server_card_url(
card::catalog_identifier(&self.inner.name),
card_url.as_str(),
)
}
fn visible(&self, name: &str, caller: &McpCaller) -> Option<&Entry> {
let entry = &self.inner.entries[*self.inner.index.get(name)?];
self.inner.executor.is_visible(entry.tool.as_ref(), caller).then_some(entry)
}
fn caller_of(&self, context: &RequestContext<RoleServer>) -> McpCaller {
match context.extensions.get::<axum::http::request::Parts>() {
Some(parts) => {
parts.extensions.get::<McpCaller>().cloned().unwrap_or_else(McpCaller::anonymous)
}
None => self.inner.local_caller.clone(),
}
}
fn task_host(&self) -> std::result::Result<&Arc<dyn McpTaskHost>, ErrorData> {
self.inner.task_host.as_ref().ok_or_else(|| {
ErrorData::new(ErrorCode::METHOD_NOT_FOUND, "this server keeps no tasks", None)
})
}
async fn call(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> std::result::Result<CallToolResponse, ErrorData> {
let parts = context.extensions.get::<axum::http::request::Parts>();
let caller = self.caller_of(&context);
let name = request.name.as_ref();
let Some(entry) = self.visible(name, &caller) else {
tracing::debug!(tool.name = %quoted(name), caller.id = caller.id(), "mcp call to an unknown tool");
return Err(ErrorData::invalid_params(
format!("unknown tool '{}'", quoted(name)),
None,
));
};
let arguments = Value::Object(request.arguments.unwrap_or_default());
if let Err(error) = entry.validator.validate(name, &arguments) {
return Ok(failed_result(name, &error).into());
}
let session_id = parts
.and_then(|parts| parts.headers.get("mcp-session-id"))
.and_then(|value| value.to_str().ok())
.map(str::to_string);
let capabilities = context.client_capabilities();
let accepts_task = self.inner.task_host.is_some()
&& capabilities.as_ref().is_some_and(|capabilities| capabilities.supports_tasks());
let accepts_input_required = context
.protocol_version()
.is_some_and(|version| version.as_str() >= ProtocolVersion::V_2026_07_28.as_str());
let can_elicit = !accepts_input_required
&& capabilities
.as_ref()
.and_then(|capabilities| capabilities.elicitation.as_ref())
.is_some_and(|elicitation| elicitation.form.is_some() || elicitation.url.is_none());
let peer = McpRequestPeer::new(
context.peer.clone(),
context.meta.get_progress_token(),
can_elicit,
);
let call = McpToolCall {
tool: Arc::clone(&entry.tool),
arguments,
caller,
request_id: request_id_string(&context.id),
session_id,
accepts_task,
accepts_input_required,
input_responses: request.input_responses,
request_state: request.request_state,
peer: Some(peer),
};
let caller_id = call.caller.id().to_string();
let run = self.inner.executor.execute(call);
let bounded = async {
match self.inner.call_timeout {
Some(limit) => tokio::time::timeout(limit, run)
.await
.unwrap_or_else(|_| Err(timeout_error(entry.tool.effect(), limit))),
None => run.await,
}
};
let outcome = tokio::select! {
outcome = bounded => outcome,
() = context.ct.cancelled() => Err(AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Cancelled,
"mcp.server.call_cancelled",
"the client cancelled the call",
)),
};
match outcome {
Ok(McpToolOutcome::Completed(value)) => Ok(completed_result(value).into()),
Ok(McpToolOutcome::Failed(error)) => {
tracing::debug!(tool.name = name, caller.id = %caller_id, error = %error.diagnostics(), "mcp tool failed");
Ok(failed_result(name, &error).into())
}
Ok(McpToolOutcome::Task(task)) if accepts_task => {
tracing::debug!(tool.name = name, caller.id = %caller_id, task.id = %task.task_id, "mcp call continues as a task");
Ok(CallToolResponse::Task(CreateTaskResult::new(task)))
}
Ok(McpToolOutcome::InputRequired { input_requests, request_state })
if accepts_input_required =>
{
let requests = (!input_requests.is_empty()).then_some(input_requests);
if requests.is_none() && request_state.is_none() {
return Err(ErrorData::internal_error(
"the call asked for input with neither questions nor state",
None,
));
}
Ok(CallToolResponse::InputRequired(InputRequiredResult::new(
requests,
request_state,
)))
}
Ok(McpToolOutcome::Task(_) | McpToolOutcome::InputRequired { .. }) => {
tracing::warn!(tool.name = name, caller.id = %caller_id, "mcp executor answered with a result the client cannot take");
Err(ErrorData::internal_error(
"the call needs a client that takes MCP tasks or input_required results",
None,
))
}
Err(error) => {
tracing::info!(tool.name = name, caller.id = %caller_id, error = %error.diagnostics(), "mcp call refused");
Err(refusal(&error))
}
}
}
}
impl ServerHandler for McpServer {
fn get_info(&self) -> ServerConfig {
let inner = &self.inner;
let mut implementation =
Implementation::new(&inner.name, &inner.version).with_description(&inner.description);
if let Some(title) = &inner.title {
implementation = implementation.with_title(title);
}
if let Some(url) = &inner.website_url {
implementation = implementation.with_website_url(url);
}
if !inner.icons.is_empty() {
implementation = implementation.with_icons(inner.icons.iter().map(rmcp_icon).collect());
}
let capabilities = if inner.task_host.is_some() {
ServerCapabilities::builder().enable_tools().enable_tasks().build()
} else {
ServerCapabilities::builder().enable_tools().build()
};
let config = InitializeResult::new(capabilities).with_server_info(implementation);
match &inner.instructions {
Some(instructions) => config.with_instructions(instructions),
None => config,
}
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> std::result::Result<ListToolsResult, ErrorData> {
let caller = self.caller_of(&context);
Ok(ListToolsResult::with_all_items(self.tool_definitions_for(&caller)))
}
fn get_tool(&self, name: &str) -> Option<rmcp::model::Tool> {
let index = *self.inner.index.get(name)?;
Some(self.inner.entries[index].definition.clone())
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> std::result::Result<CallToolResponse, ErrorData> {
self.call(request, context).await
}
async fn get_task(
&self,
request: GetTaskParams,
context: RequestContext<RoleServer>,
) -> std::result::Result<GetTaskResult, ErrorData> {
let caller = self.caller_of(&context);
let task = self.task_host()?.get(&request.task_id, &caller).await.map_err(|error| {
tracing::debug!(task.id = %quoted(&request.task_id), caller.id = caller.id(), error = %error.diagnostics(), "mcp tasks/get refused");
refusal(&error)
})?;
Ok(GetTaskResult::new(task))
}
async fn update_task(
&self,
request: UpdateTaskParams,
context: RequestContext<RoleServer>,
) -> std::result::Result<(), ErrorData> {
let caller = self.caller_of(&context);
self.task_host()?
.update(&request.task_id, &caller, request.input_responses)
.await
.map_err(|error| {
tracing::info!(task.id = %quoted(&request.task_id), caller.id = caller.id(), error = %error.diagnostics(), "mcp tasks/update refused");
refusal(&error)
})
}
async fn cancel_task(
&self,
request: CancelTaskParams,
context: RequestContext<RoleServer>,
) -> std::result::Result<(), ErrorData> {
let caller = self.caller_of(&context);
self.task_host()?.cancel(&request.task_id, &caller).await.map_err(|error| {
tracing::debug!(task.id = %quoted(&request.task_id), caller.id = caller.id(), error = %error.diagnostics(), "mcp tasks/cancel refused");
refusal(&error)
})
}
}
pub struct McpServerBuilder {
name: String,
version: String,
description: Option<String>,
title: Option<String>,
website_url: Option<String>,
repository: Option<ServerCardRepository>,
icons: Vec<ServerCardIcon>,
instructions: Option<String>,
tools: Vec<Arc<dyn Tool>>,
executor: Option<Arc<dyn McpCallExecutor>>,
governance: Option<RunConfig>,
task_host: Option<Arc<dyn McpTaskHost>>,
local_caller: McpCaller,
open_world: bool,
call_timeout: Option<Duration>,
}
impl McpServerBuilder {
fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
Self {
name: name.into(),
version: version.into(),
description: None,
title: None,
website_url: None,
repository: None,
icons: Vec::new(),
instructions: None,
tools: Vec::new(),
executor: None,
governance: None,
task_host: None,
local_caller: McpCaller::anonymous(),
open_world: true,
call_timeout: Some(DEFAULT_CALL_TIMEOUT),
}
}
pub fn description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn website_url(mut self, url: impl Into<String>) -> Self {
self.website_url = Some(url.into());
self
}
pub fn repository(mut self, repository: ServerCardRepository) -> Self {
self.repository = Some(repository);
self
}
pub fn icon(mut self, icon: ServerCardIcon) -> Self {
self.icons.push(icon);
self
}
pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
pub fn tool(mut self, tool: Arc<dyn Tool>) -> Self {
self.tools.push(tool);
self
}
pub fn tools(mut self, tools: impl IntoIterator<Item = Arc<dyn Tool>>) -> Self {
self.tools.extend(tools);
self
}
pub fn tool_governance(mut self, config: RunConfig) -> Self {
self.governance = Some(config);
self
}
pub fn executor(mut self, executor: Arc<dyn McpCallExecutor>) -> Self {
self.executor = Some(executor);
self
}
pub fn task_host(mut self, host: Arc<dyn McpTaskHost>) -> Self {
self.task_host = Some(host);
self
}
pub fn local_caller(mut self, caller: McpCaller) -> Self {
self.local_caller = caller;
self
}
pub fn open_world(mut self, open_world: bool) -> Self {
self.open_world = open_world;
self
}
pub fn call_timeout(mut self, timeout: Option<Duration>) -> Self {
self.call_timeout = timeout;
self
}
pub fn build(self) -> Result<McpServer> {
check_name(&self.name)?;
check_version(&self.version)?;
let description = self.description.ok_or_else(|| {
invalid("mcp.server.description", "set the server's description with `description(..)`")
})?;
check_text("description", &description)?;
if let Some(title) = &self.title {
check_text("title", title)?;
}
let mut entries = Vec::with_capacity(self.tools.len());
let mut index = HashMap::with_capacity(self.tools.len());
for tool in self.tools {
let name = tool.name().to_string();
if name.is_empty() {
return Err(invalid("mcp.server.tool_name", "a published tool has an empty name"));
}
if index.insert(name.clone(), entries.len()).is_some() {
return Err(invalid(
"mcp.server.duplicate_tool",
format!("two published tools are named '{name}'; MCP tool names are unique"),
));
}
let input_schema = input_schema(tool.as_ref())?;
let validator = ToolArgumentValidator::new(&Value::Object(input_schema.clone()))?;
let definition = definition(tool.as_ref(), input_schema, self.open_world);
entries.push(Entry { tool, definition, validator });
}
let executor = match (self.executor, self.governance) {
(Some(_), Some(_)) => {
return Err(invalid(
"mcp.server.executor_and_governance",
"set `executor(..)` or `tool_governance(..)`, not both: a custom executor \
governs its own calls, so the governance config would be ignored",
));
}
(Some(executor), None) => executor,
(None, config) => {
Arc::new(GovernedExecutor::new(self.name.clone(), config.unwrap_or_default()))
as Arc<dyn McpCallExecutor>
}
};
Ok(McpServer {
inner: Arc::new(Inner {
name: self.name,
version: self.version,
description,
title: self.title,
website_url: self.website_url,
repository: self.repository,
icons: self.icons,
instructions: self.instructions,
entries,
index,
executor,
task_host: self.task_host,
local_caller: self.local_caller,
call_timeout: self.call_timeout,
}),
})
}
}
fn definition(tool: &dyn Tool, input_schema: JsonObject, open_world: bool) -> rmcp::model::Tool {
let declared = tool.annotations();
let hint = |key: &str| declared.and_then(|hints| hints.get(key)).and_then(Value::as_bool);
let title = declared.and_then(|hints| hints.get("title")).and_then(Value::as_str);
let annotations = match title {
Some(title) => ToolAnnotations::with_title(title),
None => ToolAnnotations::new(),
};
let annotations = match tool.effect() {
ToolEffect::ReadOnly => annotations.read_only(true).idempotent(true).destructive(false),
ToolEffect::Idempotent => annotations
.read_only(false)
.idempotent(true)
.destructive(hint("destructiveHint").unwrap_or(true)),
_ => annotations
.read_only(false)
.idempotent(false)
.destructive(hint("destructiveHint").unwrap_or(true)),
}
.open_world(hint("openWorldHint").unwrap_or(open_world));
let mut definition = rmcp::model::Tool::new(
tool.name().to_string(),
tool.description().to_string(),
Arc::new(input_schema),
)
.with_annotations(annotations);
if let Some(title) = title {
definition = definition.with_title(title);
}
if let Some(Value::Object(output)) = tool.response_schema()
&& output.get("type").and_then(Value::as_str) == Some("object")
{
definition = definition.with_raw_output_schema(Arc::new(output));
}
definition
}
fn input_schema(tool: &dyn Tool) -> Result<JsonObject> {
match tool.parameters_schema() {
None => Ok(JsonObject::from_iter([("type".to_string(), json!("object"))])),
Some(Value::Object(mut schema)) => match schema.get("type") {
None => {
schema.insert("type".to_string(), json!("object"));
Ok(schema)
}
Some(Value::String(kind)) if kind == "object" => Ok(schema),
Some(other) => Err(invalid(
"mcp.server.input_schema",
format!(
"tool '{}' declares parameters of type {other}; an MCP tool's parameters are \
a JSON object, so wrap them in an object schema",
tool.name()
),
)),
},
Some(_) => Err(invalid(
"mcp.server.input_schema",
format!(
"tool '{}' declares a parameters schema that is not a JSON object",
tool.name()
),
)),
}
}
fn completed_result(value: Value) -> CallToolResult {
let text = match &value {
Value::String(text) => text.clone(),
other => other.to_string(),
};
let mut result = CallToolResult::success(vec![ContentBlock::text(text)]);
if value.is_object() {
result.structured_content = Some(value);
}
result
}
fn failed_result(tool: &str, error: &AdkError) -> CallToolResult {
let response = tool_error_response(tool, error, false);
let text = response["error"].as_str().unwrap_or("the tool failed").to_string();
CallToolResult::error(vec![ContentBlock::text(text)])
}
fn refusal(error: &AdkError) -> ErrorData {
let code = match error.category {
ErrorCategory::InvalidInput | ErrorCategory::NotFound | ErrorCategory::Unsupported => {
ErrorCode::INVALID_PARAMS
}
ErrorCategory::Unauthorized
| ErrorCategory::Forbidden
| ErrorCategory::RateLimited
| ErrorCategory::Timeout
| ErrorCategory::Unavailable
| ErrorCategory::Cancelled
| ErrorCategory::Internal
| ErrorCategory::ResourceExhausted
| ErrorCategory::Conflict => ErrorCode::INTERNAL_ERROR,
};
let message = if error.category.is_rejection() {
let mut chars = error.message.chars();
let head: String = chars.by_ref().take(TOOL_ERROR_MESSAGE_LIMIT).collect();
let cut = if chars.next().is_some() { "… (truncated)" } else { "" };
format!("{}: {head}{cut}", error.redacted())
} else {
error.redacted()
};
let mut data = json!({
"category": error.category.to_string(),
"code": error.code,
"retryable": error.is_retryable(),
});
if let Some(after) = error.retry.retry_after_ms {
data["retryAfterMs"] = json!(after);
}
ErrorData::new(code, message, Some(data))
}
fn timeout_error(effect: ToolEffect, limit: Duration) -> AdkError {
let error = AdkError::timeout(
ErrorComponent::Tool,
"mcp.server.call_timeout",
format!("the call ran past the server's {} ms limit", limit.as_millis()),
);
if effect.is_retry_safe() { error } else { error.with_retry(RetryHint::default()) }
}
fn request_id_string(id: &rmcp::model::RequestId) -> String {
match id {
rmcp::model::NumberOrString::Number(number) => number.to_string(),
rmcp::model::NumberOrString::String(text) => text.to_string(),
}
}
fn quoted(name: &str) -> Cow<'_, str> {
match name.char_indices().nth(QUOTED_NAME_LIMIT) {
Some((end, _)) => Cow::Owned(format!("{}…", &name[..end])),
None => Cow::Borrowed(name),
}
}
fn rmcp_icon(icon: &ServerCardIcon) -> rmcp::model::Icon {
let mut converted = rmcp::model::Icon::new(&icon.src);
if let Some(mime_type) = &icon.mime_type {
converted = converted.with_mime_type(mime_type);
}
if let Some(sizes) = &icon.sizes {
converted = converted.with_sizes(sizes.clone());
}
if let Some(theme) = icon.theme {
converted = converted.with_theme(match theme {
IconTheme::Light => rmcp::model::IconTheme::Light,
IconTheme::Dark => rmcp::model::IconTheme::Dark,
});
}
converted
}
fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
AdkError::new(ErrorComponent::Tool, ErrorCategory::InvalidInput, code, message)
}
fn check_name(name: &str) -> Result<()> {
let valid = (3..=200).contains(&name.len())
&& name.split_once('/').is_some_and(|(namespace, server)| {
!namespace.is_empty()
&& !server.is_empty()
&& namespace.bytes().all(|b| b.is_ascii_alphanumeric() || b".-".contains(&b))
&& server.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
});
if valid {
Ok(())
} else {
Err(invalid(
"mcp.server.name",
format!(
"server name '{name}' is not a reverse-DNS name with one '/', such as \
'com.example/shop' (SEP-2127)"
),
))
}
}
fn check_version(version: &str) -> Result<()> {
let is_range = version.contains(['^', '~', '>', '<', '=', '*', ' '])
|| version.split('.').any(|part| part.eq_ignore_ascii_case("x"));
if version.is_empty() || version.len() > 255 || is_range {
return Err(invalid(
"mcp.server.version",
format!(
"server version '{version}' must be one version of at most 255 characters, not a range, such as '1.0.2'"
),
));
}
Ok(())
}
fn check_text(field: &str, value: &str) -> Result<()> {
let length = value.chars().count();
if (1..=100).contains(&length) {
Ok(())
} else {
Err(invalid(
"mcp.server.card_text",
format!("the server's {field} has {length} characters; SEP-2127 allows 1 to 100"),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::FunctionTool;
fn tool(name: &str) -> Arc<dyn Tool> {
Arc::new(FunctionTool::new(name, "a tool", |_ctx, _args| async { Ok(json!({})) }))
}
fn server() -> McpServerBuilder {
McpServer::builder("com.example/shop", "1.0.0").description("Shop")
}
#[test]
fn names_follow_the_card_schema() {
for good in ["com.example/shop", "io.github.acme-co/shop_v2.1", "a/b"] {
assert!(check_name(good).is_ok(), "{good}");
}
for bad in ["shop", "com.example/", "/shop", "com/example/shop", "com.example/sh op", "ab"]
{
assert!(check_name(bad).is_err(), "{bad}");
}
}
#[test]
fn versions_reject_ranges() {
for good in ["1.0.0", "2.1.0-alpha", "2026.10"] {
assert!(check_version(good).is_ok(), "{good}");
}
for bad in ["", "^1.2.3", "~1.2.3", ">=1.2.3", "1.x", "1.*"] {
assert!(check_version(bad).is_err(), "{bad}");
}
}
#[test]
fn the_description_is_required_and_bounded() {
let missing = McpServer::builder("com.example/shop", "1.0.0").build().unwrap_err();
assert_eq!(missing.code, "mcp.server.description");
let long = server().description("x".repeat(101)).build().unwrap_err();
assert_eq!(long.code, "mcp.server.card_text");
}
#[test]
fn duplicate_tool_names_are_refused() {
let error = server().tool(tool("quote")).tool(tool("quote")).build().unwrap_err();
assert_eq!(error.code, "mcp.server.duplicate_tool");
}
#[test]
fn a_tool_without_parameters_takes_an_empty_object() {
let built = server().tool(tool("quote")).build().unwrap();
assert_eq!(
Value::Object((*built.tool_definitions()[0].input_schema).clone()),
json!({ "type": "object" })
);
}
#[test]
fn refusals_keep_internal_messages_back() {
let internal = AdkError::unavailable(
ErrorComponent::Tool,
"orders.db",
"connect postgres://admin:secret@db.internal failed",
);
let data = refusal(&internal);
assert_eq!(data.code, ErrorCode::INTERNAL_ERROR);
assert_eq!(data.message, "tool.unavailable (orders.db)");
assert_eq!(
data.data,
Some(json!({ "category": "unavailable", "code": "orders.db", "retryable": true }))
);
let denied = AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Forbidden,
"awp.capability.tier",
"this capability needs the known tier",
);
assert_eq!(
refusal(&denied).message,
"tool.forbidden (awp.capability.tier): this capability needs the known tier"
);
let invalid_input = invalid("x.y", "bad");
assert_eq!(refusal(&invalid_input).code, ErrorCode::INVALID_PARAMS);
}
#[test]
fn a_timed_out_non_idempotent_call_is_not_retryable() {
let limit = Duration::from_secs(1);
assert!(!timeout_error(ToolEffect::NonIdempotent, limit).is_retryable());
assert!(timeout_error(ToolEffect::ReadOnly, limit).is_retryable());
}
#[test]
fn quoted_names_are_bounded() {
let long = "a".repeat(500);
assert_eq!(quoted(&long).chars().count(), QUOTED_NAME_LIMIT + 1);
assert_eq!(quoted("quote"), "quote");
}
}