use crate::api::generated::types::McpResourceName;
use crate::error::Error;
use crate::mcp_server::McpServerConnection;
use rmcp::model::ResourceContents;
#[derive(Clone)]
pub struct CompletionEvaluatedPrompt {
pub parts: Vec<PromptPart>,
}
#[derive(Clone)]
pub struct ResourceData {
mcp_server_connection: McpServerConnection,
resource_uri: String,
}
#[derive(Clone)]
pub enum PromptPart {
String(String),
Resource(ResourceData),
AllResources(McpServerConnection),
}
impl CompletionEvaluatedPrompt {
pub fn new() -> Self {
Self { parts: Vec::new() }
}
pub fn from_string(string: impl Into<String>) -> Self {
Self {
parts: vec![PromptPart::String(string.into())],
}
}
pub fn string(mut self, string: impl Into<String>) -> Self {
self.parts.push(PromptPart::String(string.into()));
self
}
pub fn resource(
mut self,
mcp_server_connection: McpServerConnection,
resource_uri: impl Into<String>,
) -> Self {
self.parts.push(PromptPart::Resource(ResourceData {
mcp_server_connection,
resource_uri: resource_uri.into(),
}));
self
}
pub fn coral_resource(
self,
mcp_server_connection: McpServerConnection,
resource: McpResourceName,
) -> Self {
self.resource(mcp_server_connection, resource.to_string())
}
pub fn all_resources(mut self, mcp_server_connection: McpServerConnection) -> Self {
self.parts
.push(PromptPart::AllResources(mcp_server_connection));
self
}
fn resource_contents_to_string(resource_contents: Vec<ResourceContents>) -> String {
resource_contents
.iter()
.map(|x| {
match x {
ResourceContents::TextResourceContents { text, .. } => text,
ResourceContents::BlobResourceContents { blob, .. } => blob,
}
.clone()
})
.collect::<Vec<_>>()
.join("\n")
}
pub async fn evaluate(&self) -> Result<String, Error> {
let mut buffer = String::new();
for part in &self.parts {
buffer.push_str(
match part {
PromptPart::String(string) => string.clone(),
PromptPart::Resource(resource_data) => Self::resource_contents_to_string(
resource_data
.mcp_server_connection
.read_resource(&resource_data.resource_uri)
.await?,
),
PromptPart::AllResources(mcp_server_connection) => {
Self::resource_contents_to_string(
mcp_server_connection.get_resources().await?,
)
}
}
.as_str(),
);
buffer.push('\n');
}
Ok(buffer)
}
}