use rmcp::model::{CallToolResult, ContentBlock, JsonObject, MetaObject};
use serde::{Deserialize, Serialize};
use std::future::Future;
pub const RESULT_STATUS_META_KEY: &str = "symforge/result_status";
pub const RESULT_STATUS_CONTRACT_VERSION: u8 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OutcomeClass {
Found,
NotFound,
Ambiguous,
InvalidRequest,
EmptyResult,
InternalFailure,
}
impl OutcomeClass {
pub const ALL: [Self; 6] = [
Self::Found,
Self::NotFound,
Self::Ambiguous,
Self::InvalidRequest,
Self::EmptyResult,
Self::InternalFailure,
];
pub const fn as_str(self) -> &'static str {
match self {
Self::Found => "found",
Self::NotFound => "not_found",
Self::Ambiguous => "ambiguous",
Self::InvalidRequest => "invalid_request",
Self::EmptyResult => "empty_result",
Self::InternalFailure => "internal_failure",
}
}
pub const fn is_error(self) -> bool {
matches!(self, Self::InvalidRequest | Self::InternalFailure)
}
}
pub const PROJECT_EVIDENCE_META_KEY: &str = "symforge/project_evidence";
pub const PROJECT_EVIDENCE_HEADER: &str = "x-symforge-project-evidence";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectEvidence {
pub project_id: String,
pub project_name: String,
pub canonical_root: Option<String>,
pub generation: u64,
pub index_state: String,
pub load_source: String,
pub index_files: usize,
pub index_symbols: usize,
}
pub fn project_evidence_matches_selector(
evidence: &ProjectEvidence,
selector: Option<&str>,
) -> bool {
let Some(root) = evidence.canonical_root.as_deref() else {
return false;
};
let computed = crate::daemon::project_key(std::path::Path::new(root));
if computed != evidence.project_id {
return false;
}
let Some(selector) = selector.filter(|value| !value.trim().is_empty()) else {
return true;
};
if selector.starts_with("project-v1-") {
evidence.project_id == selector
} else {
evidence.project_id == selector || evidence.project_name == selector
}
}
tokio::task_local! {
static PROJECT_EVIDENCE: std::cell::RefCell<Option<ProjectEvidence>>;
}
pub async fn with_project_evidence_scope<F, T>(seed: Option<ProjectEvidence>, future: F) -> T
where
F: Future<Output = T>,
{
PROJECT_EVIDENCE
.scope(std::cell::RefCell::new(seed), future)
.await
}
pub fn record_project_evidence(evidence: ProjectEvidence) {
let _ = PROJECT_EVIDENCE.try_with(|cell| *cell.borrow_mut() = Some(evidence));
}
pub fn clear_project_evidence() {
let _ = PROJECT_EVIDENCE.try_with(|cell| *cell.borrow_mut() = None);
}
pub fn current_project_evidence() -> Option<ProjectEvidence> {
PROJECT_EVIDENCE
.try_with(|cell| cell.borrow().clone())
.ok()
.flatten()
}
pub fn attach_project_evidence_meta(meta: &mut Option<MetaObject>) {
let meta = meta.get_or_insert_with(|| MetaObject(JsonObject::new()));
if meta.0.contains_key(PROJECT_EVIDENCE_META_KEY) {
return;
}
let value = match current_project_evidence().map(|e| serde_json::to_value(&e)) {
Some(Ok(value)) => value,
_ => serde_json::json!({
"bound": false,
"reason": "project_evidence_unavailable",
}),
};
meta.0.insert(PROJECT_EVIDENCE_META_KEY.to_string(), value);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResultStatus {
pub contract_version: u8,
pub outcome_class: OutcomeClass,
}
impl ResultStatus {
pub const fn new(outcome_class: OutcomeClass) -> Self {
Self {
contract_version: RESULT_STATUS_CONTRACT_VERSION,
outcome_class,
}
}
pub fn into_call_tool_result(self, human_text: impl Into<String>) -> CallToolResult {
let mut meta = JsonObject::new();
meta.insert(
RESULT_STATUS_META_KEY.to_string(),
serde_json::to_value(self).expect("ResultStatus must serialize to JSON"),
);
if let Some(evidence) = current_project_evidence()
&& let Ok(value) = serde_json::to_value(&evidence)
{
meta.insert(PROJECT_EVIDENCE_META_KEY.to_string(), value);
}
let content = vec![ContentBlock::text(human_text.into())];
let result = if self.outcome_class.is_error() {
CallToolResult::error(content)
} else {
CallToolResult::success(content)
};
result.with_meta(Some(MetaObject(meta)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn project_evidence_selector_matching_preserves_nonblank_whitespace() {
let root = std::path::Path::new("/work/repo");
let evidence = ProjectEvidence {
project_id: crate::daemon::project_key(root),
project_name: "repo".to_string(),
canonical_root: Some(root.display().to_string()),
generation: 1,
index_state: "ready".to_string(),
load_source: "memory".to_string(),
index_files: 1,
index_symbols: 1,
};
assert!(project_evidence_matches_selector(&evidence, Some("repo")));
assert!(
!project_evidence_matches_selector(&evidence, Some("repo ")),
"a legal trailing space must not be normalized onto another project name"
);
assert!(project_evidence_matches_selector(&evidence, Some(" ")));
}
}