use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use multicast_mcp_protocol::structured::{
McpStructuredShape, project_output_schema, project_structured_content, projection_metadata,
};
use serde_json::{Map, Value, json};
use super::{
McpDiscovery, McpResourceReadRequest, McpResourceRegistry, McpResourceRequest,
McpResourceSubscriptionRequest, McpServeOptions, McpSubscriptionListenRequest, McpToolFilter,
};
use crate::cli::ConfigOptions;
use crate::command::{McpPeer, McpResultContent};
use crate::schema::FieldMeta;
use crate::tool::{
ConfigSource, EnvironmentSource, ToolCallControl, ToolCallOptions, ToolCallOutcome,
ToolCatalog, ToolDefinition, ToolEvent,
};
enum ResolvedCall {
Discovery(Value),
Command(String, Option<Map<String, Value>>),
}
pub(crate) struct SharedTool {
definition: ToolDefinition,
output_shape: Option<McpStructuredShape>,
pub(crate) name: String,
pub(crate) description: String,
pub(crate) title: Option<String>,
pub(crate) icons: Vec<Value>,
pub(crate) meta: BTreeMap<String, Value>,
pub(crate) result_meta: BTreeMap<String, Value>,
pub(crate) direct: bool,
pub(crate) input_schema: Map<String, Value>,
pub(crate) output_schema: Option<Map<String, Value>>,
pub(crate) annotations: Option<Value>,
pub(crate) read_only: bool,
pub(crate) instructions: Option<String>,
pub(crate) result_content: Vec<McpResultContent>,
pub(crate) task_support: crate::command::McpTaskSupport,
}
fn shared_tool(definition: &ToolDefinition) -> Result<SharedTool, crate::errors::Error> {
let projection = definition.output_schema.as_ref().map(project_output_schema)
.transpose().map_err(|error| {
crate::errors::Error::Multicast(crate::errors::MulticastError {
message: format!("Cannot publish MCP output schema for {}: {error}", definition.name),
code: error.code().to_string(),
hint: Some("Use JSON Schema 2020-12 for non-object output, or declare an object-root output schema.".to_string()),
retryable: false,
exit_code: None,
cause: Some(Box::new(error)),
})
})?;
let annotations = definition.annotations.as_ref().map(|annotations| {
let mut wire = Map::new();
if let Some(title) = &annotations.title {
wire.insert("title".to_string(), json!(title));
}
for (key, hint) in [
("readOnlyHint", annotations.read_only_hint),
("destructiveHint", annotations.destructive_hint),
("idempotentHint", annotations.idempotent_hint),
("openWorldHint", annotations.open_world_hint),
] {
if let Some(hint) = hint {
wire.insert(key.to_string(), Value::Bool(hint));
}
}
Value::Object(wire)
});
Ok(SharedTool {
definition: definition.clone(),
output_shape: projection.as_ref().map(|projection| projection.shape),
name: definition.name.clone(),
description: definition.description.clone(),
title: definition.title.clone(),
icons: definition.icons.clone(),
meta: definition.meta.clone(),
result_meta: definition.result_meta.clone(),
direct: definition.direct,
input_schema: definition
.input_schema
.as_object()
.cloned()
.unwrap_or_default(),
output_schema: projection
.as_ref()
.and_then(|projection| projection.schema.as_object().cloned()),
read_only: definition
.annotations
.as_ref()
.and_then(|annotations| annotations.read_only_hint)
== Some(true),
annotations,
instructions: definition.instructions.clone(),
result_content: definition.result_content.clone(),
task_support: definition.task_support,
})
}
pub(crate) struct ServerSource<'a> {
pub(crate) open_telemetry: bool,
pub(crate) name: &'a str,
pub(crate) version: &'a str,
pub(crate) commands: &'a BTreeMap<String, crate::cli::CommandEntry>,
pub(crate) root_middleware: &'a [crate::middleware::MiddlewareFn],
pub(crate) env_fields: &'a [FieldMeta],
pub(crate) globals_fields: &'a [FieldMeta],
pub(crate) config: Option<&'a ConfigOptions>,
pub(crate) prompt_guides: &'a [crate::prompt::PromptGuide],
pub(crate) cli: Option<&'a crate::cli::Cli>,
}
impl<'a> ServerSource<'a> {
pub(crate) fn from_cli(cli: &'a crate::cli::Cli) -> Self {
Self {
open_telemetry: cli.open_telemetry,
name: &cli.name,
version: cli.version.as_deref().unwrap_or("0.0.0"),
commands: &cli.commands,
root_middleware: &cli.middleware,
env_fields: &cli.env_fields,
globals_fields: &cli.globals_fields,
config: cli.config.as_ref(),
prompt_guides: &cli.prompt_guides,
cli: Some(cli),
}
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn from_parts(
name: &'a str,
version: &'a str,
commands: &'a BTreeMap<String, crate::cli::CommandEntry>,
root_middleware: &'a [crate::middleware::MiddlewareFn],
env_fields: &'a [FieldMeta],
) -> Self {
Self {
open_telemetry: true,
name,
version,
commands,
root_middleware,
env_fields,
globals_fields: &[],
config: None,
prompt_guides: &[],
cli: None,
}
}
}
pub(crate) fn wildcard_matches(pattern: &str, value: &str) -> bool {
if pattern == "*" {
return true;
}
let parts = pattern.split('*').collect::<Vec<_>>();
if parts.len() == 1 {
return pattern == value;
}
let mut offset = 0;
for (index, part) in parts.iter().enumerate() {
if part.is_empty() {
continue;
}
let Some(found) = value[offset..].find(part) else {
return false;
};
if index == 0 && !pattern.starts_with('*') && found != 0 {
return false;
}
offset += found + part.len();
}
pattern.ends_with('*') || parts.last().is_some_and(|part| value.ends_with(part))
}
fn tool_is_exposed(name: &str, filter: &McpToolFilter) -> bool {
let included = filter.include.is_empty()
|| filter
.include
.iter()
.any(|pattern| wildcard_matches(pattern, name));
let excluded = filter
.exclude
.iter()
.any(|pattern| wildcard_matches(pattern, name));
included && !excluded
}
pub(crate) fn direct_tool(tool: &SharedTool) -> Value {
let mut wire = Map::new();
wire.insert("name".to_string(), json!(tool.name));
wire.insert("description".to_string(), json!(tool.description));
if let Some(title) = &tool.title {
wire.insert("title".to_string(), json!(title));
}
if !tool.icons.is_empty() {
wire.insert("icons".to_string(), Value::Array(tool.icons.clone()));
}
wire.insert(
"inputSchema".to_string(),
Value::Object(tool.input_schema.clone()),
);
if let Some(schema) = &tool.output_schema {
wire.insert("outputSchema".to_string(), Value::Object(schema.clone()));
}
if let Some(annotations) = &tool.annotations {
wire.insert("annotations".to_string(), annotations.clone());
}
if let Some(metadata) = tool_metadata(tool) {
wire.insert("_meta".to_string(), Value::Object(metadata));
}
Value::Object(wire)
}
fn tool_metadata(tool: &SharedTool) -> Option<Map<String, Value>> {
let mut metadata = tool.output_shape.and_then(projection_metadata);
if !tool.meta.is_empty() {
metadata.get_or_insert_default().extend(tool.meta.clone());
}
if let Some(instructions) = &tool.instructions {
metadata
.get_or_insert_default()
.insert("instructions".to_string(), json!(instructions));
}
metadata
}
pub(crate) fn progressive_tools() -> Vec<Value> {
let search = json!({
"type": "object",
"properties": {
"query": { "type": "string", "default": "" },
"limit": { "type": "number", "default": 5 },
"offset": { "type": "number", "default": 0 }
}
});
let inspect = json!({
"type": "object",
"properties": { "name": { "type": "string" } },
"required": ["name"]
});
let execute = json!({
"type": "object",
"properties": {
"name": { "type": "string" },
"arguments": { "type": "object", "additionalProperties": true }
},
"required": ["name"]
});
[
(
"search_tools",
"Search or page through available tools by capability. Returns names and descriptions without loading their schemas. Inspect a result before calling it.",
search,
true,
),
(
"get_tool_details",
"Inspect one tool returned by search_tools. Returns its complete input schema and metadata.",
inspect,
true,
),
(
"call_read_tool",
"Execute a tool marked read-only after inspecting its schema with get_tool_details.",
execute.clone(),
true,
),
(
"call_write_tool",
"Execute a writable or unclassified tool after inspecting its schema with get_tool_details.",
execute,
false,
),
]
.into_iter()
.map(|(name, description, schema, read_only)| {
json!({
"name": name,
"description": description,
"inputSchema": schema,
"annotations": {
"readOnlyHint": read_only,
"destructiveHint": !read_only,
"idempotentHint": read_only,
"openWorldHint": !matches!(name, "search_tools" | "get_tool_details"),
},
})
})
.collect()
}
fn text_block(text: String) -> Value {
json!({ "type": "text", "text": text })
}
fn call_tool_result(
content: Vec<Value>,
structured: Option<Value>,
is_error: bool,
meta: Option<Value>,
) -> Value {
let mut wire = Map::new();
wire.insert("resultType".to_string(), json!("complete"));
wire.insert("content".to_string(), Value::Array(content));
if let Some(structured) = structured {
wire.insert("structuredContent".to_string(), structured);
}
wire.insert("isError".to_string(), Value::Bool(is_error));
if let Some(meta) = meta {
wire.insert("_meta".to_string(), meta);
}
Value::Object(wire)
}
fn structured_result(value: Value) -> Value {
call_tool_result(
vec![text_block(value.to_string())],
Some(value),
false,
None,
)
}
fn error_text_result(message: String) -> Value {
call_tool_result(
vec![text_block(json!({ "error": message }).to_string())],
None,
true,
None,
)
}
pub(crate) fn discovery_result(
name: &str,
arguments: Option<Map<String, Value>>,
tools: &HashMap<String, Arc<SharedTool>>,
) -> Result<Option<Value>, String> {
let arguments = arguments.unwrap_or_default();
match name {
"search_tools" => {
let query = arguments
.get("query")
.and_then(Value::as_str)
.unwrap_or("")
.to_lowercase();
let page_arg = |name: &str, default: u64| {
let value = arguments
.get(name)
.and_then(Value::as_u64)
.unwrap_or(default);
usize::try_from(value).unwrap_or(usize::MAX)
};
let offset = page_arg("offset", 0);
let limit = page_arg("limit", 5);
let mut matches = tools
.values()
.filter(|tool| {
query.is_empty()
|| tool.name.to_lowercase().contains(&query)
|| tool.description.to_lowercase().contains(&query)
})
.map(|tool| {
json!({
"name": tool.name,
"description": tool.description,
"annotations": tool.annotations,
})
})
.collect::<Vec<_>>();
matches.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str()));
let total = matches.len();
let page = matches
.into_iter()
.skip(offset)
.take(limit)
.collect::<Vec<_>>();
Ok(Some(structured_result(json!({
"tools": page,
"nextOffset": (offset + page.len() < total).then_some(offset + page.len()),
}))))
}
"get_tool_details" => {
let tool_name = arguments
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| "Missing tool name".to_string())?;
let tool = tools
.get(tool_name)
.ok_or_else(|| format!("Unknown tool: {tool_name}"))?;
let mut details = json!({
"name": tool.name,
"description": tool.description,
"title": tool.title,
"icons": tool.icons,
"inputSchema": Value::Object(tool.input_schema.clone()),
"outputSchema": tool.output_schema.clone().map(Value::Object),
"annotations": tool.annotations,
"instructions": tool.instructions,
});
if let Some(metadata) = tool_metadata(tool) {
details["_meta"] = Value::Object(metadata);
}
Ok(Some(structured_result(details)))
}
"call_read_tool" | "call_write_tool" => {
let tool_name = arguments
.get("name")
.and_then(Value::as_str)
.ok_or_else(|| "Missing tool name".to_string())?;
let tool = tools
.get(tool_name)
.ok_or_else(|| format!("Unknown tool: {tool_name}"))?;
if name == "call_read_tool" && !tool.read_only {
return Ok(Some(error_text_result(format!(
"Tool is not read-only: {tool_name}"
))));
}
if name == "call_write_tool" && tool.read_only {
return Ok(Some(error_text_result(format!(
"Tool is read-only: {tool_name}"
))));
}
Ok(None)
}
_ => Err(format!("Unknown discovery tool: {name}")),
}
}
fn formatted_cta(name: &str, cta: crate::output::CtaBlock) -> Value {
let commands = cta
.commands
.into_iter()
.map(|entry| match entry {
crate::output::CtaEntry::Simple(command) => json!({
"command": format!("{name} {command}"),
}),
crate::output::CtaEntry::Detailed {
command,
description,
} => {
let command = if command == name || command.starts_with(&format!("{name} ")) {
command
} else {
format!("{name} {command}")
};
json!({ "command": command, "description": description })
}
})
.collect::<Vec<_>>();
json!({
"description": cta.description.unwrap_or_else(|| "Suggested commands:".to_string()),
"commands": commands,
})
}
fn render_cta(cta: &Value) -> String {
let mut lines = vec![
cta["description"]
.as_str()
.unwrap_or("Suggested commands:")
.to_string(),
];
for command in cta["commands"].as_array().into_iter().flatten() {
let value = command["command"].as_str().unwrap_or("");
let description = command["description"]
.as_str()
.map(|description| format!(" # {description}"))
.unwrap_or_default();
lines.push(format!(" {value}{description}"));
}
lines.join("\n")
}
pub(crate) fn tool_result_success(
name: &str,
data: Value,
cta: Option<crate::output::CtaBlock>,
structured: bool,
presentation: &[McpResultContent],
) -> Value {
let text = serde_json::to_string(&data).unwrap_or_else(|_| "null".to_string());
let cta = cta.map(|cta| formatted_cta(name, cta));
let text = cta
.as_ref()
.map(|cta| format!("{text}\n\n{}", render_cta(cta)))
.unwrap_or(text);
let mut content = vec![text_block(text)];
for item in presentation {
match item {
McpResultContent::Image {
data_pointer,
mime_type_pointer,
}
| McpResultContent::Audio {
data_pointer,
mime_type_pointer,
} => {
let Some(image_data) = data.pointer(data_pointer).and_then(Value::as_str) else {
continue;
};
let Some(mime_type) = data.pointer(mime_type_pointer).and_then(Value::as_str)
else {
continue;
};
content.push(json!({
"type": if matches!(item, McpResultContent::Audio { .. }) { "audio" } else { "image" },
"data": image_data,
"mimeType": mime_type,
}));
}
McpResultContent::ResourceLink {
uri_pointer,
name_pointer,
mime_type_pointer,
} => {
let Some(uri) = data.pointer(uri_pointer).and_then(Value::as_str) else {
continue;
};
let Some(name) = data.pointer(name_pointer).and_then(Value::as_str) else {
continue;
};
let Some(mime_type) = data.pointer(mime_type_pointer).and_then(Value::as_str)
else {
continue;
};
content.push(json!({
"type": "resource_link", "uri": uri, "name": name, "mimeType": mime_type,
}));
}
}
}
call_tool_result(
content,
structured.then_some(data),
false,
cta.map(|cta| json!({ "cta": cta })),
)
}
fn tool_result_error(
name: &str,
data: Value,
cta: Option<crate::output::CtaBlock>,
structured: bool,
) -> Value {
let cta = cta.map(|cta| formatted_cta(name, cta));
let mut content = vec![text_block(data.to_string())];
if let Some(cta) = &cta {
content.push(text_block(render_cta(cta)));
}
call_tool_result(
content,
structured.then_some(data),
true,
cta.map(|cta| json!({ "cta": cta })),
)
}
pub(crate) fn tool_call_result(
name: &str,
outcome: ToolCallOutcome,
structured: bool,
presentation: &[McpResultContent],
) -> Value {
match outcome {
ToolCallOutcome::Ok { data, cta } => {
tool_result_success(name, data, cta, structured, presentation)
}
ToolCallOutcome::InputRequired {
input_requests,
request_state,
meta,
} => {
let mut wire = Map::new();
wire.insert("resultType".to_string(), json!("input_required"));
if !input_requests.is_empty() {
wire.insert("inputRequests".to_string(), json!(input_requests));
}
if let Some(request_state) = request_state {
wire.insert("requestState".to_string(), json!(request_state));
}
if !meta.is_empty() {
wire.insert("_meta".to_string(), json!(meta));
}
Value::Object(wire)
}
ToolCallOutcome::Error {
code,
message,
retryable,
field_errors,
cta,
exit_code,
} => {
let message = if message.is_empty() {
"Command failed".to_string()
} else {
message
};
let mut data = json!(crate::output::ExecuteError {
code,
message,
retryable,
field_errors,
});
if let Some(exit_code) = exit_code {
data["exit_code"] = json!(exit_code);
}
tool_result_error(name, data, cta, structured)
}
}
}
pub(crate) fn progress_message(event: ToolEvent) -> String {
match event {
ToolEvent::Chunk { data } => {
serde_json::to_string(&data).unwrap_or_else(|_| "null".to_string())
}
ToolEvent::Progress { message, .. } | ToolEvent::Log { message, .. } => message,
}
}
pub(crate) struct CallContext {
pub(crate) protocol_version: String,
pub(crate) request: Option<crate::command::RequestContext>,
pub(crate) request_meta: Option<Value>,
pub(crate) client_capabilities: Option<Value>,
pub(crate) input_responses: Option<Value>,
pub(crate) request_state: Option<String>,
pub(crate) peer: Option<McpPeer>,
pub(crate) control: ToolCallControl,
pub(crate) environment: EnvironmentSource,
}
#[derive(Clone)]
pub(crate) struct ToolServer {
pub(crate) server_name: String,
pub(crate) server_version: String,
catalog: ToolCatalog,
tools_by_name: Arc<HashMap<String, Arc<SharedTool>>>,
pub(crate) tool_list: Arc<Vec<Value>>,
pub(crate) instructions: Option<String>,
discovery: McpDiscovery,
result_mapper: Option<super::McpResultMapper>,
capabilities: BTreeMap<String, Value>,
resources: Arc<McpResourceRegistry>,
peer: Option<crate::command::McpPeer>,
pub(crate) standards: multicast_mcp_protocol::McpStandardSet,
prompts: Arc<Vec<crate::prompt::PromptGuide>>,
skills: Arc<super::McpSkillBundle>,
}
impl ToolServer {
pub(crate) fn new(
source: &ServerSource<'_>,
options: &McpServeOptions,
) -> Result<Self, crate::errors::Error> {
let catalog = ToolCatalog::from_parts(
source.name.to_string(),
Some(source.version.to_string()),
source.commands,
source.root_middleware,
source.env_fields,
source.globals_fields,
source.config,
)
.map(|catalog| catalog.with_open_telemetry(source.open_telemetry))
.map_err(|error| {
crate::errors::Error::Other(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
error.to_string(),
)))
})?;
#[cfg(not(target_arch = "wasm32"))]
let resolved = catalog
.resolved()
.filter(|tool| tool_is_exposed(&tool.definition.name, &options.tools))
.map(|tool| shared_tool(&tool.definition))
.collect::<Result<Vec<_>, _>>()?;
#[cfg(target_arch = "wasm32")]
let resolved = catalog
.definitions()
.iter()
.filter(|definition| tool_is_exposed(&definition.name, &options.tools))
.map(shared_tool)
.collect::<Result<Vec<_>, _>>()?;
let mut names = HashSet::new();
if options.tools.discovery == McpDiscovery::Progressive {
for tool in resolved.iter().filter(|tool| tool.direct) {
if matches!(
tool.name.as_str(),
"search_tools" | "get_tool_details" | "call_read_tool" | "call_write_tool"
) {
return Err(crate::errors::Error::Other(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"MCP tool name is reserved for progressive discovery: {}",
tool.name
),
))));
}
}
}
for tool in &resolved {
if !names.insert(tool.name.clone()) {
return Err(crate::errors::Error::Other(Box::new(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("Duplicate MCP tool name: {}", tool.name),
))));
}
}
let mut tool_list: Vec<Value> = if options.tools.discovery == McpDiscovery::Direct {
resolved.iter().map(direct_tool).collect()
} else {
progressive_tools()
};
if options.tools.discovery == McpDiscovery::Progressive {
tool_list.extend(resolved.iter().filter(|tool| tool.direct).map(direct_tool));
}
let skills = match &options.skills {
super::McpSkillPublication::Off => super::McpSkillBundle::new(),
super::McpSkillPublication::Custom(bundle) => bundle.clone(),
super::McpSkillPublication::Generated => match source.cli {
Some(cli) => super::McpSkillBundle::generated(
&cli.installed_skill_files(1),
source.prompt_guides,
)?,
None => super::McpSkillBundle::generated(&[], source.prompt_guides)?,
},
};
let tools_by_name = resolved
.into_iter()
.map(|tool| (tool.name.clone(), Arc::new(tool)))
.collect();
Ok(Self {
server_name: source.name.to_string(),
server_version: source.version.to_string(),
catalog,
tools_by_name: Arc::new(tools_by_name),
tool_list: Arc::new(tool_list),
instructions: options.instructions.clone(),
discovery: options.tools.discovery,
result_mapper: options.result_mapper.clone(),
capabilities: options.capabilities.clone(),
resources: Arc::new(options.resources.clone()),
peer: options.peer.clone(),
standards: options.standards.clone(),
prompts: Arc::new(source.prompt_guides.to_vec()),
skills: Arc::new(skills),
})
}
pub(crate) fn capabilities(&self) -> Value {
let mut capabilities = Map::new();
capabilities.insert("prompts".to_string(), json!({}));
let mut resources = Map::new();
if self.resources.subscribe.is_some() || self.resources.unsubscribe.is_some() {
resources.insert("subscribe".to_string(), Value::Bool(true));
}
capabilities.insert("resources".to_string(), Value::Object(resources));
capabilities.insert("tools".to_string(), json!({}));
if !self.skills.is_empty() {
capabilities.insert(
"extensions".to_string(),
json!({ (super::SKILLS_EXTENSION): { "directoryRead": true } }),
);
}
for (key, value) in &self.capabilities {
match (capabilities.get_mut(key), value) {
(Some(Value::Object(existing)), Value::Object(added)) if key == "extensions" => {
existing.extend(added.clone());
}
_ => {
capabilities.insert(key.clone(), value.clone());
}
}
}
Value::Object(capabilities)
}
pub(crate) fn subscription_listen_supported(&self) -> bool {
self.resources.listen.is_some()
}
pub(crate) fn list_prompts(&self) -> Value {
let prompts = self
.prompts
.iter()
.map(crate::prompt::mcp_prompt_entry)
.collect::<Vec<_>>();
json!({ "resultType": "complete", "prompts": prompts })
}
pub(crate) fn get_prompt(
&self,
name: &str,
arguments: Option<&Map<String, Value>>,
) -> Result<Value, String> {
let guide = self
.prompts
.iter()
.find(|guide| guide.name == name)
.ok_or_else(|| format!("Prompt not found: {name}"))?;
let task = arguments
.and_then(|arguments| arguments.get(crate::prompt::TASK_ARGUMENT))
.and_then(Value::as_str);
let mut result = crate::prompt::mcp_prompt_result(guide, task, |tool| {
self.tools_by_name.contains_key(tool)
});
result["resultType"] = json!("complete");
Ok(result)
}
pub(crate) fn is_skill_file(&self, uri: &str) -> bool {
self.skills.read(uri).is_some()
}
pub(crate) fn skills_published(&self) -> bool {
!self.skills.is_empty()
}
pub(crate) fn list_skills(
&self,
cursor: Option<&str>,
) -> Result<Value, super::McpResourceError> {
self.skills.list(cursor)
}
pub(crate) fn get_skill(&self, uri: &str) -> Result<Value, super::McpResourceError> {
self.skills.get(uri)
}
pub(crate) fn read_directory(
&self,
uri: &str,
cursor: Option<&str>,
) -> Result<Value, super::McpResourceError> {
self.skills.read_directory(uri, cursor)
}
pub(crate) fn list_resources(&self) -> Value {
let resources = self
.resources
.resources
.iter()
.map(|resource| serde_json::to_value(resource).expect("MCP resource is serializable"))
.chain(self.skills.resources())
.collect::<Vec<_>>();
json!({ "resultType": "complete", "resources": resources })
}
pub(crate) fn list_resource_templates(&self) -> Value {
let templates = self
.resources
.templates
.iter()
.map(|template| {
serde_json::to_value(template).expect("MCP resource template is serializable")
})
.collect::<Vec<_>>();
json!({ "resultType": "complete", "resourceTemplates": templates })
}
pub(crate) async fn read_resource(
&self,
uri: String,
context: ResourceContext,
) -> Result<Value, super::McpResourceError> {
if let Some(value) = self.skills.read(&uri) {
return Ok(value);
}
let Some(reader) = &self.resources.read else {
return Err(super::McpResourceError {
code: -32602,
message: "Resource reading is not supported".to_string(),
data: None,
});
};
let result = reader
.read(McpResourceReadRequest {
uri,
context: context.into_request(),
})
.await?;
let mut value = serde_json::to_value(result).expect("MCP resource result is serializable");
value["resultType"] = json!("complete");
Ok(value)
}
pub(crate) async fn set_resource_subscription(
&self,
uri: String,
subscribe: bool,
context: ResourceContext,
) -> Result<Value, super::McpResourceError> {
let handler = if subscribe {
&self.resources.subscribe
} else {
&self.resources.unsubscribe
};
let Some(handler) = handler else {
return Err(super::McpResourceError {
code: -32602,
message: "Resource subscriptions are not supported".to_string(),
data: None,
});
};
handler
.handle(McpResourceSubscriptionRequest {
uri,
context: context.into_request(),
})
.await?;
Ok(json!({ "resultType": "complete" }))
}
pub(crate) async fn listen_subscriptions(
&self,
notifications: Value,
resource_uris: Vec<String>,
cursor: Option<String>,
context: ResourceContext,
) -> Result<futures::stream::BoxStream<'static, Value>, super::McpResourceError> {
let Some(handler) = &self.resources.listen else {
return Err(super::McpResourceError {
code: -32601,
message: "Subscriptions listen is not supported".to_string(),
data: None,
});
};
handler
.listen(McpSubscriptionListenRequest {
notifications,
resource_uris,
cursor,
context: context.into_request(),
})
.await
}
fn resolve_call(
&self,
name: String,
arguments: Option<Map<String, Value>>,
) -> Result<ResolvedCall, String> {
if self.discovery != McpDiscovery::Progressive
|| self
.tools_by_name
.get(&name)
.is_some_and(|tool| tool.direct)
{
return Ok(ResolvedCall::Command(name, arguments));
}
if let Some(result) = discovery_result(&name, arguments.clone(), &self.tools_by_name)? {
return Ok(ResolvedCall::Discovery(result));
}
let mut execute = arguments.unwrap_or_default();
let name = execute
.remove("name")
.and_then(|value| value.as_str().map(ToString::to_string))
.ok_or_else(|| "Missing tool name".to_string())?;
let arguments = execute
.remove("arguments")
.and_then(|value| value.as_object().cloned());
Ok(ResolvedCall::Command(name, arguments))
}
pub(crate) fn task_allowed(&self, name: &str, arguments: Option<&Map<String, Value>>) -> bool {
matches!(
self.resolve_call(name.to_string(), arguments.cloned()),
Ok(ResolvedCall::Command(command, _))
if self.tools_by_name.get(&command).is_some_and(|tool| {
tool.task_support == crate::command::McpTaskSupport::Allowed
})
)
}
#[cfg(feature = "mcp-files")]
pub(crate) fn command_input_schema(
&self,
name: &str,
arguments: Option<&Map<String, Value>>,
) -> Option<(Map<String, Value>, bool)> {
match self.resolve_call(name.to_string(), arguments.cloned()) {
Ok(ResolvedCall::Command(command, _)) => self
.tools_by_name
.get(&command)
.map(|tool| (tool.input_schema.clone(), command != name)),
_ => None,
}
}
pub(crate) fn any_task_tool(&self) -> bool {
self.tools_by_name
.values()
.any(|tool| tool.task_support == crate::command::McpTaskSupport::Allowed)
}
pub(crate) async fn call_tool(
&self,
name: String,
arguments: Option<Map<String, Value>>,
context: CallContext,
) -> Result<Value, String> {
let (tool_name, arguments) = match self.resolve_call(name, arguments)? {
ResolvedCall::Discovery(result) => return Ok(result),
ResolvedCall::Command(name, arguments) => (name, arguments),
};
let tool = self
.tools_by_name
.get(&tool_name)
.ok_or_else(|| format!("Unknown tool: {tool_name}"))?;
let input_options: BTreeMap<String, Value> =
arguments.unwrap_or_default().into_iter().collect();
let peer = context.peer.or_else(|| self.peer.clone());
let outcome = self
.catalog
.call(
&tool_name,
input_options,
ToolCallOptions {
environment: context.environment,
config: ConfigSource::Auto,
globals: None,
request: context.request,
mcp: Some(crate::command::McpCallContext {
protocol_version: Some(context.protocol_version.clone()),
request_meta: context.request_meta,
client_capabilities: context.client_capabilities,
input_responses: context.input_responses,
request_state: context.request_state,
peer,
}),
control: context.control,
},
)
.await;
let mapping = self
.result_mapper
.as_ref()
.map(|mapper| {
mapper.map(super::McpResultContext {
tool: &tool.definition,
outcome: &outcome,
})
})
.unwrap_or_default();
let success = matches!(outcome, ToolCallOutcome::Ok { .. });
let mut result = tool_call_result(
&self.server_name,
outcome,
tool.output_schema.is_some(),
&tool.result_content,
);
if success && let Some(shape) = tool.output_shape {
let data = result["structuredContent"].take();
match project_structured_content(data, shape) {
Ok(projected) => {
result["structuredContent"] = projected;
if let Some(metadata) = projection_metadata(shape) {
if !result["_meta"].is_object() {
result["_meta"] = json!({});
}
result["_meta"].as_object_mut().unwrap().extend(metadata);
}
}
Err(error) => {
return Ok(tool_call_result(
&self.server_name,
ToolCallOutcome::Error {
code: error.code().to_string(),
message: error.to_string(),
retryable: Some(false),
field_errors: None,
cta: None,
exit_code: None,
},
false,
&[],
));
}
}
}
if success && !tool.result_meta.is_empty() {
if !result["_meta"].is_object() {
result["_meta"] = json!({});
}
result["_meta"]
.as_object_mut()
.unwrap()
.extend(tool.result_meta.clone());
}
if let Some(structured_content) = mapping.structured_content {
result["structuredContent"] = structured_content;
}
if let Some(content) = mapping.content {
result["content"] = Value::Array(content);
}
if !mapping.meta.is_empty() {
if !result["_meta"].is_object() {
result["_meta"] = json!({});
}
result["_meta"]
.as_object_mut()
.unwrap()
.extend(mapping.meta);
}
if let Some(is_error) = mapping.is_error {
result["isError"] = json!(is_error);
}
if let Some(content) = result.get_mut("content").and_then(Value::as_array_mut) {
content.retain(|block| match block["type"].as_str() {
Some("audio") => context.protocol_version.as_str() >= "2025-03-26",
Some("resource_link") => context.protocol_version.as_str() >= "2025-06-18",
_ => true,
});
}
Ok(result)
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct ResourceContext {
pub(crate) request_id: Option<Value>,
pub(crate) request: Option<crate::command::RequestContext>,
pub(crate) protocol_version: Option<String>,
pub(crate) request_meta: Option<Value>,
pub(crate) client_capabilities: Option<Value>,
pub(crate) input_responses: Option<Value>,
pub(crate) request_state: Option<String>,
pub(crate) peer: Option<McpPeer>,
}
impl ResourceContext {
fn into_request(self) -> McpResourceRequest {
McpResourceRequest {
request_id: self.request_id,
request: self.request,
protocol_version: self.protocol_version,
request_meta: self.request_meta,
client_capabilities: self.client_capabilities,
input_responses: self.input_responses,
request_state: self.request_state,
peer: self.peer,
}
}
}